css - Multi-line flexbox list with text-overflow: ellipsis
问题描述
I would like to achieve the attached list style in HTML5/CSS.
The single-line items can easily be done using flexbox (see below). However, I cannot quite figure out how to achieve the double-line items: If I allow wrapping, the "List Item Title" will no longer be truncated (ellipsis)...
Should I use CSS grid? Or is that overkill?
Here is my flexbox-single-line-implementation:
ul {
padding: 0;
border: 1px solid red;
list-style-type: none;
}
li {
display: flex;
margin: 0;
border-bottom: 1px solid gray;
}
div.icon {
flex-shrink: 0;
width: 20px;
height: 20px;
margin: 15px;
background-color: lightcoral;
}
span.title {
flex-grow: 1;
flex-shrink: 1;
margin: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
span.tag {
flex-shrink: 0;
margin: 15px;
}
span.second-line {
margin: 15px;
}
<ul>
<li>
<div class="icon"></div>
<span class="title">List Item Title</span>
<span class="tag">Some tag</span>
</li>
<li>
<div class="icon"></div>
<span class="title">Very Super Long List Item Title With Added Characters to Ensure Truncation</span>
<span class="tag">Some tag</span>
</li>
<li>
<div class="icon"></div>
<span class="title">List Item Title</span>
</li>
</ul>
解决方案
您可以通过在 li 中使用两个子 Div 来实现结果,并为两个子 Div 使用单独的 Flex,而不是在 li 中。在下面找到适合我的代码。
代码:
ul {
padding: 0;
border: 1px solid red;
list-style-type: none;
}
li {
margin: 0;
border-bottom: 1px solid gray;
}
div.icon {
flex-shrink: 0;
width: 20px;
height: 20px;
margin: 15px;
background-color: lightcoral;
}
span.title {
flex-grow: 1;
flex-shrink: 1;
margin: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
span.tag {
flex-shrink: 0;
margin: 15px;
}
span.second-line {
margin: 15px;
}
.mainHeading {
display: flex;
}
.subHeading {
display: block;
}
<ul>
<li>
<div class="mainHeading">
<div class="icon"></div>
<span class="title">List Item Title</span>
<span class="tag">Some tag</span>
</div>
</li>
<li>
<div class="mainHeading">
<div class="icon"></div>
<span class="title">Very Super Long List Item Title With Added Characters to Ensure Truncation</span>
<span class="tag">Some tag</span>
</div>
<div class="subHeading">
<span class="title">List Item Sub Title</span>
<span class="tag">Some another tag</span>
</div>
</li>
<li>
<div class="mainHeading">
<div class="icon"></div>
<span class="title">List Item Title</span>
</div>
</li>
</ul>
推荐阅读
- wpf - WPF 添加菜单与标题栏一致
- json - 使用 Kotlin 的序列化库编写一堆数据类来解析一个简单的 JSON 真的很乏味。有更好的办法吗?
- go - 使用 go 更新/覆盖而不是插入插入到 bigquery
- google-apps-script - 循环浏览 2 个谷歌表格
- c++ - 如何调用 clang 以使用当前操作系统 GLIBC?
- android - Android 构建自 7 月 20 日以来显着放缓,构建期间外部库中也会出现 502 Bad Gateway
- oauth-2.0 - OpenID 连接成功的响应在重定向 uri 和访问令牌之间有 #
- sql - 通过连接表(SQL)从两个 id 中获取名称
- php - 用mysql将多列中的多行组合起来
- css - CSS多个动画具有不同的延迟