带徽章的列表组
在本教程中,我们将创建一个带有徽章的列表组模式,徽章用于指示计数。

依赖项
列表项应与徽章一起显示。徽章应右对齐并垂直居中。无论内容是单行文本还是多行文本,徽章都必须垂直居中。
示例
点击下面代码块中的“Play”按钮,在 MDN Playground 中编辑示例。
html
<ul class="list-group">
<li>
Item One
<span class="badge">2</span>
</li>
<li>
Item Two
<span class="badge">10</span>
</li>
<li>
Item Three
<span class="badge">9</span>
</li>
<li>
Item Four
<span class="badge">0</span>
</li>
</ul>
css
body {
font: 1.2em / 1.5 sans-serif;
padding: 0;
margin: 1em;
}
.list-group {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid #cccccc;
border-radius: 0.5em;
width: 20em;
}
.list-group li {
border-top: 1px solid #cccccc;
padding: 0.5em;
display: flex;
justify-content: space-between;
align-items: center;
}
.list-group li:first-child {
border-top: 0;
}
.list-group .badge {
background-color: rebeccapurple;
color: white;
font-weight: bold;
font-size: 80%;
border-radius: 10em;
min-width: 1.5em;
padding: 0.25em;
text-align: center;
}
已做出的选择
Flexbox 使这种特定模式变得简单,并且也便于更改布局。
为确保文本和徽章正确对齐,我使用 justify-content 属性,其值为 space-between。这会将所有额外空间放置在项目之间。在实时示例中,如果您删除此属性,您会看到徽章移动到文本较短的项目中文本的末尾。
为了水平对齐内容,我使用 align-items 属性在交叉轴上对齐文本和徽章。如果您希望徽章与内容的顶部对齐,请将其更改为 align-items: flex-start。