我有一个全宽div
,其中包含多个li
,我正在尝试将它们放入具有相等空格的父div中,并强制LI
从左到右显示,有时它的破坏和显示下一行,是否有可能使它填充div并在响应时保持它?
这是JSFiddle示例
请建议
.msearch_cities {
float: left;
width: 100%;
}
.msearch_cities > ul {
font-size: 0;
list-style: none;
margin: 0;
padding: 0;
}
.msearch_cities > ul > li {
border: 1px solid #b4b4b4;
color: #404040;
display: inline-block;
font-size: 16px;
list-style: none;
margin: 0 5px 5px 0;
padding: 5px;
vertical-align: top;
}

<div class="msearch_cities">
<ul>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
<li>Aligarh</li>
<li>Allahabad</li>
<li>Allahabad</li>
</ul>
</div>
&#13;
答案 0 :(得分:3)
所以你需要的是flex
。您只需使用给定代码更新代码
flex-wrap: wrap;
flex-direction: row;
justify-content: space-between;
display: inline-flex;
因此更新的css 代码将
.msearch_cities > ul {
font-size: 0;
list-style: none;
margin: 0;
padding: 0;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-between;
display: inline-flex;
}
直播demo
要拉伸元素,请使用弹性框。 Flex-direction用于将它们保持在一行中,justify-content
将设置元素之间的空间。
详细了解弹性框启动here
答案 1 :(得分:0)
这可以使用JQuery轻松实现,获取父级的宽度,定义子级的最小宽度并计算每个元素的宽度,就像我在下面所做的那样
//Set the minimum width of child element
var minItemWid = 85;
//get the width of main container
var wrapWid = $(".msearch_cities").width();
//Get the number of items in a row and divide by minumum width of child above
var numOfItem = parseInt(wrapWid / minItemWid);
//Get the remaining space after the child element in a row
var itemWid = wrapWid % minItemWid;
//Remaining space added in to the child width
var remainSpce = itemWid / numOfItem;
//now assign the child width
$(".msearch_cities > ul > li").css("width",minItemWid + remainSpce);
此外,将上述代码也放在window.resize中。
编辑这是一个有效的JSfiddle
您可以在js中设置变量的最小宽度以与容器完全匹配