CSS 拉伸列表项 <li> 以填充 <ul> 的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13397135/
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-29 20:46:58  来源:igfitidea点击:

Stretch list items <li> to fill the width of <ul>

css

提问by AlexStack

I have an unordered list (<ul>) with various number of items (<li>) in it. I want to use one CSS styling that allows the items to stretch to the width of the list.

我有一个无序列表 ( <ul>),其中包含不同数量的项目 ( <li>)。我想使用一种 CSS 样式,允许项目拉伸到列表的宽度。

This is what I have:

这就是我所拥有的:

enter image description here

在此处输入图片说明

This is what I want:

这就是我要的:

enter image description here

在此处输入图片说明

HTML:

HTML:

These 4 items should fill the width:<br/>
<ul id="ul1">
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
</ul>
<br/>
These 5 items should fill the width:<br/>
<ul id="ul2">
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
</ul>
<br/>
And so on and so forth...

Here is the JSFiddleto get you started.

这是帮助您入门的JSFiddle

Note: I don't want to hard-code the widthin CSS. Note: If you are wondering about the use-case, this is a navigation structure in a responsive design and I want the list items to always fill up the available width no matter what is the resolution.

注意:我不想在 CSS 中硬编码width。注意:如果您想知道用例,这是响应式设计中的导航结构,我希望列表项始终填满可用宽度,无论分辨率如何。

回答by Rohit Azad

DemoHI now you can do this

演示HI 现在您可以执行此操作

Used todisplay :tableand display:table-cell

曾经display :tabledisplay:table-cell

as like this

像这样

Css

css

ul {
    border:1px dotted black;
    padding: 0;
    display:table;
    width:100%;
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
li {
    background-color: red;
    display:table-cell;
}
li:nth-child(2n) {
    background-color: #0F0;
}

Now define your parentdisplay:table;or width:100%;and define your childdisplay:table-cell;

现在定义你的父母display:table;width:100%;定义你的孩子display:table-cell;

Demo

演示

回答by Victor Nolêto

Easy solution with

简单的解决方案

ul {
    display: flex;
}

ul li {
    width: 100%;
}

回答by irejwanul

I've got the simplest solution. <ul style="padding: 0;"> <li style="list-style-type: none;margin:0;"></li> </ul>

我有最简单的解决方案。 <ul style="padding: 0;"> <li style="list-style-type: none;margin:0;"></li> </ul>

回答by UBS prakash

#ul1 {
display: block;
padding: 0;
list-style: none;
}

li-Class{
width: 100%
}

Note: display can be inline-block with width:100% and this code is for those who are looking to arrange li block wise.

注意:显示可以是宽度为 100% 的内联块,此代码适用于希望以块方式排列的人。