CSS 如何使 <li> 项目宽度适合文本长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21512523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:47:44  来源:igfitidea点击:

How to make the <li> item width fit the text length?

csstwitter-bootstraptwitter-bootstrap-3

提问by CodeShark

How can I make the <li>item width fit the text length in Bootstrap 3? My menu item is shorter than the text which causes my class="active"to look ugly.

如何使<li>项目宽度适合 Bootstrap 3 中的文本长度?我的菜单项比文本短,这导致我class="active"看起来很难看。

This is the navbar in which it occurs:

这是它发生的导航栏:

<div id="menu" class="col-md-1">
<ul class="nav nav-pills nav-stacked">
<li class="active"><a href="#">Startseite</a></li>
<li><a href="kontakt.php">Kontakt</a></li>
</ul>
</div>

回答by NoobEditor

make a .custom_liclass and give

做一个.custom_li类,并给

.custom_li{
   display:inline-block;
}

EDIT

编辑

To force same size, i'll suggest using max-widthand place it under some media-query

为了强制相同的大小,我建议使用max-width并将其放在一些media-query

li{
    display: inline-block;
    max-width:50%; /* limit width */
    word-break:break-all; /* wrap extended text*/
    border:1px solid red /* demo */
}

demo here

演示在这里

some optional things

一些可选的东西

some optional things

一些可选的东西

回答by plong0

When I tried display: inline-block;it removes the bullet.

当我尝试时,display: inline-block;它会移除子弹。

Instead, I use float:left;to have them only as wide as text, while preserving the bullet. Optionally, add clear:both;to keep it as a vertical list with each item on a new line.

相反,我使用float:left;它们的宽度与文本一样宽,同时保留项目符号。(可选)添加clear:both;以将其保留为垂直列表,每个项目都在一个新行上。

CSS

CSS

.my-list > li {
    float: left;
    clear: both; /* remove this if you want them flowing inline */
}

HTML

HTML

<ul class="my-list">
    <li>First Item</li>
    <li>Second Item</li>
    <li>Third Item</li>
    <li>Fourth Item</li>
</ul>

回答by Manish Sundriyal

If the display: inline-block;or display: block;is messing up the alignment.
Then just use width: fit-content;

如果display: inline-block;display: block;弄乱了对齐方式。
然后只需使用width: fit-content;

回答by Marcel

Prevent it becoming a block by adding display: inline-block;to the proper element. Post more code and preferably CSS if you want details.

通过添加display: inline-block;到适当的元素来防止它成为一个块。如果您需要详细信息,请发布更多代码,最好是 CSS。