为何设置display:inline后CSS width属性异常?如何修复?
问题:设置
<ul>和<li>为display:inline后子元素宽度异常的解决办法 我最近遇到一个问题:原本我的列表布局是正常的,当我给<ul>和<li>添加display:inline属性移除默认的block显示后,发现#grand-child-1和#grand-child-2的width属性完全失效了,无法按照设置的30%宽度显示。
原始正常代码(无display:inline)
ul,li{ list-style-type:none; padding:0; /*display:inline;*/ } #parent{ width:100%; /*height:50px;*/ background-color:red; } #child{ width:50%; height:100%; background-color:yellow; } #grand-child-1,#grand-child-2 { width:30%; height:100%; float:left; } #grand-child-2{ background-color:green; } #grand-child-1{ background-color:blue; }
<div id="parent"> <ul id="child"> <li id="grand-child-1">title 1</li> <li id="grand-child-2">title-2</li> <li id="grand-child-3">title-3</li> </ul> </div>
修改后出问题的代码(添加display:inline)
ul,li{ list-style-type:none; padding:0; display:inline; } #parent{ width:100%; /*height:50px;*/ background-color:red; } #child{ width:50%; height:100%; background-color:yellow; } #grand-child-1,#grand-child-2 { width:30%; height:100%; float:left; } #grand-child-2{ background-color:green; } #grand-child-1{ background-color:blue; }
<div id="parent"> <ul id="child"> <li id="grand-child-1">title 1</li> <li id="grand-child-2">title-2</li> <li id="grand-child-3">title-3</li> </ul> </div>
问题原因分析
这个问题的核心在于行内元素(display:inline)的特性限制:
- 行内元素的宽度和高度由自身内容决定,无法通过
width和height属性强制设置; - 当你把
<ul>设为display:inline后,它变成了行内元素,即便子元素设置了float:left,父元素的行内特性也会导致子元素的宽度设置无法正常生效。
解决方案
根据你的需求,我提供几种可行的解决方式:
方案1:使用display:inline-block实现横向排列(推荐)
这种方式既保留了横向排列的效果,又支持设置宽高,是最常用的列表横向布局方案:
ul,li{ list-style-type:none; padding:0; } #parent{ width:100%; /*height:50px;*/ background-color:red; } #child{ width:50%; height:100%; background-color:yellow; } #grand-child-1,#grand-child-2 { width:30%; height:100%; display:inline-block; } #grand-child-2{ background-color:green; } #grand-child-1{ background-color:blue; }
- 说明:
inline-block兼具行内元素的横向排列特性和块级元素的宽高可控特性,子元素的width和height能正常生效。
方案2:保留浮动,恢复<ul>的块级属性
如果你想继续使用浮动布局,只需要去掉<ul>和<li>的display:inline,同时给父元素<ul>添加清除浮动的样式,避免高度塌陷:
ul,li{ list-style-type:none; padding:0; } #parent{ width:100%; /*height:50px;*/ background-color:red; } #child{ width:50%; height:100%; background-color:yellow; overflow:hidden; /* 清除浮动,让父元素包裹子元素 */ } #grand-child-1,#grand-child-2 { width:30%; height:100%; float:left; } #grand-child-2{ background-color:green; } #grand-child-1{ background-color:blue; }
- 说明:
<ul>保持默认的block显示,浮动的子元素可以正常设置宽度,overflow:hidden用于清除浮动,解决父元素高度为0的问题。
方案3:若必须让<ul>为行内元素,改为display:inline-block
如果你的场景确实需要<ul>是行内级元素,把它的display设为inline-block而不是inline,这样它既能支持宽高设置,子元素的浮动也能正常工作:
ul{ list-style-type:none; padding:0; display:inline-block; } li{ list-style-type:none; padding:0; } #parent{ width:100%; /*height:50px;*/ background-color:red; } #child{ width:50%; height:100%; background-color:yellow; overflow:hidden; } #grand-child-1,#grand-child-2 { width:30%; height:100%; float:left; } #grand-child-2{ background-color:green; } #grand-child-1{ background-color:blue; }
内容的提问来源于stack exchange,提问作者Afsal Khan
相关产品推荐
相关产品推荐

