首页 > 解决方案 > 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?

enter image description here

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>

标签: cssflexboxhtml-lists

解决方案


您可以通过在 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>


推荐阅读