使用 css 设置<li>内容的宽度

  • 本文关键字:li css 设置 使用 css
  • 更新时间 :
  • 英文 :


我需要一些帮助。。。这是我的小提琴:http://jsfiddle.net/taglegacy/Lrczay80/.

我正在尝试使li的宽度与li中最长文本的宽度相匹配。我尝试过使用这个解决方案,尽管我似乎无法使其适用于我的css代码,如何将css宽度设置为最长文本长度。

如果您能提供帮助,我们将不胜感激!

这是CSS:

ol.nlist
{
counter-reset: li;
padding: 10px;
}
ol.nlist li
{
position: relative;
margin: 0 0 0px 2em;
padding: 4px 8px;
list-style: none;
border-top: 2px solid #af1f1c;
background: #f6f6f6;
}
ol.nlist li:before
{
content: counter(li);
counter-increment: li; 
position: absolute;
top: -2px;
left: -2em;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 2em;
margin-right: 8px;
padding: 4px;
height: 30px;
border-top: 2px solid #af1f1c;
color: #fff;
background: #af1f1c;
font-weight: bold;
font-family: "Helvetica Neue", Arial, sans-serif;
text-align: center;
}
li.nlist ol, li.nlist ul
{
margin-top: 6px;
width: 100%;
}
ol.nlist ol li:last-child
{
margin-bottom: 0;
}
.ac
{
text-decoration: none;
color: #444;
}

这是HTML

<ol class="nlist">
<li><a class="ac" href="#1">Test Short Text</a></li>
<li><a class="ac" href="#2">Slightly Longer Text to Test</a></li>
<li><a class="ac" href="#3">Really Really Long Long Long Text to Give the Effect  Wanted</a></li>
</ol>

只需将这些display: table; table-layout: fixed;添加到您的ol:

ol.nlist
{
    counter-reset: li; /* Initiate a counter */
    padding: 10px;
    display: table;
    table-layout: fixed;
}

演示

请注意,table-layout: fixed;是可选的。与其说是风格,不如说是性能的提升。

更改此项:

ol.nlist li
{
position: relative;
margin: 0 0 0px 2em;
padding: 4px 8px;
list-style: none;
border-top: 2px solid #af1f1c;
background: #f6f6f6;
width: 760px;
}

到此:

ol.nlist li
{
position: relative;
margin: 0 0 0px 2em;
padding: 4px 8px;
list-style: none;
border-top: 2px solid #af1f1c;
background: #f6f6f6;
width: auto;
}

更改此项:

ol.nlist
{
counter-reset: li; /* Initiate a counter */
padding: 10px;
}

到此:

ol.nlist
{
counter-reset: li; /* Initiate a counter */
padding: 10px;
display:table;
}

ol.nlist添加position: absolute;

ol.nlist li中,删除width并添加以下两个属性:

display: block;
white-space: nowrap;

结果如下:http://jsfiddle.net/y1cv84c3/

最新更新