我需要实现一些要求:
动态绘制一个 li
元素列表,其中可以包含不同长度的文本。所有太长而无法在一行中显示的元素都需要替换为 ...
。我已经通过以下 css 实现了这一点:
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
通常此面包屑导航包含 1-5 个元素。第一个和最后一个元素应始终显示全文。
如何在不包括最后一个元素的宽度的情况下计算 li
元素的最大宽度?像这样的东西:
calc((100% - width-last-element)/<li-el-qty>-1
我试过以下方法:
body {
font-family: Helvetica, Arial, sans-serif;
margin: 0;
padding: 1em;
background-color: rgb(227, 227, 227);
white-space: nowrap;
overflow: hidden;
}
/* Regular breadcrumbs */
ul {
list-style-type: none;
margin: 0;
padding: 2em;
color: #333;
}
li {
display: inline-block;
position: relative;
padding-right: 2em;
margin: 0;
text-decoration: none;
display: inline-block;
color: #333;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 8em;
}
li:after {
content: '>';
position: absolute;
display: inline-block;
right: 0;
width: 2em;
text-align: center;
}
li:nth-last-child(1) {
text-decoration: underline;
font-weight: bold;
text-overflow: clip;
overflow: visible;
}
<ul class="bread">
<li>MERSEDES</li>
<!--
-->
<li>Main transmission section1</li>
<!--
-->
<li>Second Transmissio Section</li>
<!--
-->
<li>Another to view</li>
<!--
-->
<li>Final link the hierarchy</li>
<!--
-->
<li>Current section viewAAAAA</li>
</ul>
https://codepen.io/nolik/pen/mKpWYm
我也试过根据这样的元素数量设置动态宽度:
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
max-width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
max-width: 25%;
}
但都没有用。
最佳答案
您可以通过使用 flexbox
及其 grow
和 shrink
属性来实现您想要的结果。
需要进行以下修改:
- 将
display: flex;
添加到ul
。这将使它成为一个flex
容器 - 将
flex: 0 1 10%;
添加到li
。这将告诉li
不增长而是收缩初始长度为10%
- 使用规则
flex: 0 0 auto;
添加选择器li:first-child
。这将确保第一个li
保持其初始大小并且不会缩小 - 使用规则
flex: 1 0 auto;
添加选择器li:last-child
。这将确保最后一个li
增长以填充可用空间
body {
font-family: Helvetica, Arial, sans-serif;
margin: 0;
padding: 1em;
background-color: rgb(227, 227, 227);
white-space: nowrap;
overflow: hidden;
}
ul {
list-style-type: none;
margin: 0;
padding: 2em;
color: #333;
display: flex;
}
li {
position: relative;
padding-right: 2em;
margin: 0;
text-decoration: none;
color: #333;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 0 1 10%;
}
li:after {
content: '>';
position: absolute;
right: 0;
width: 2em;
text-align: center;
}
li:nth-last-child(1) {
text-decoration: underline;
font-weight: bold;
text-overflow: clip;
overflow: visible;
}
li:first-child {
flex: 0 0 auto;
}
li:last-child {
flex: 1 0 auto;
}
<ul class="bread">
<li>MERSEDES</li>
<li>Main transmission section1</li>
<li>Second Transmissio Section</li>
<li>Another to view</li>
<li>Final link the hierarchy</li>
<li>Current section viewAAAAA</li>
</ul>
关于html - 列表元素的动态宽度计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50923240/