我有一个侧边栏,其中包含一个类别列表,每个类别后面都有一个徽章,其中包含许多未读文章。由于类别是用户定义的,它们有时可能比侧边栏的宽度长,因此需要进行椭圆化处理。
现在,我的代码会对项目进行椭圆化处理,但对整行进行处理,包括徽章,我希望保持可见。我还希望标签旁边有徽章,而不是向右浮动。
ul {
width: 6em;
background: pink;
padding: 0.5em;
list-style: none;
}
li {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
color: gray;
}
<ul>
<li>Short <span class="badge">5</span></li>
<li>Much longer item <span class="badge">13</span></li>
<li>Another <span class="badge">2</span></li>
</ul>
我想出了一个基于flexbox的解决方案,但它需要一个额外的元素。有一个更好的方法吗?
当我们将标签包装到单独的元素中时,我们可以使用flexbox:
ul {
width: 6em;
background: pink;
padding: 0.5em;
list-style: none;
}
li {
display: flex;
white-space: nowrap;
}
.label {
text-overflow: ellipsis;
overflow: hidden;
margin-right: 0.25em;
}
.badge {
color: gray;
}
<ul>
<li><span class="label">Short</span><span class="badge">5</span></li>
<li><span class="label">Much longer item</span><span class="badge">13</span></li>
<li><span class="label">Another</span><span class="badge">2</span></li>
</ul>
这是另一个灵活的解决方案,可以选择许多“徽章”或元素
.wrapper {
display: flex;
flex-direction: column;
padding: 10px;
margin: 30px 0;
background: rgba(0, 0, 0, 0.1);
}
.flex {
display: flex;
justify-content: space-between;
align-items: center;
}
.will-truncate {
flex: 1;
min-width: 0;
}
.will-truncate h2 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.badges > div {
width: 30px;
height: 30px;
border-radius: 10px;
background: cornflowerblue;
display: inline-flex;
}
/*nonessentials*/
body {
padding: 40px;
}
h2 {
font-size: 1rem;
font-weight: normal;
}
<div class="wrapper">
<div class="flex will-truncate">
<h2>This is a long string that is OK to truncate please and thank you</h2>
<div class="flex badges">
<div></div>
<div></div>
<div></div>
</div>
</div>
</div>