float 属性决定一个盒子(一个元素)是否应该浮动。
浮动允许通过将块级元素向右或者向左推动来水平定位元素。
在HTML父元素高度比子元素高度小,是什么原因?
HTML中子元素运行到了父元素外面,怎么处理?
在HTML中,里面的内容运行出外面来了,是什么原因?
检查内部元素是否设置了浮动,并且外部元素没有清除浮动。
下面是解决方法:
注意,浮动后,外层的父元素高度将不包含子元素高度。
如果要撑开父元素,需要使用clear进行清除。
例如:
默认情况下,父元素的高度等于所有块级子元素的高度之和:
<style> .parent{ border:2px solid red } .child1{ background:green; height:15px;} .child2{ background:blue; height:20px; } </style> <div class="parent"> <div class="child1"> hello</div> <div class="child2"> world</div> </div>
hello
world
设置float 浮动, 父元素的高度等于没有浮动的块级子元素的高度之和, 这里等于child1元素的高度:
<style> .parent{ border:2px solid red } .child1{ background:green; width:100px; height:25px;} .child2{ background:blue; width:100px; height:35px; float:left} </style> <div class="parent"> <div class="child1"> hello</div> <div class="child2"> world</div> </div>
hello
world
使用clear清除浮动,父元素将包括所有子元素:
<style> .parent{ border:2px solid red } .parent:after, .parent:before { display: table; content: " "; } .parent:after{ clear: both; } .child1{ background:green; width:100px; height:25px;} .child2{ background:blue; width:100px; height:35px; float:left} </style> <div class="parent"> <div class="child1"> hello</div> <div class="child2"> world</div> </div>
hello
world
或者使用display: flex;
灵活布局:
<style> .parent{ border:2px solid red } .parent { display: flex; } .child1{ background:green; width:100px; height:25px;} .child2{ background:blue; width:100px; height:35px; float:left} </style> <div class="parent"> <div class="child1"> hello</div> <div class="child2"> world</div> </div>
日期:2020-09-17 00:09:15 来源:oir作者:oir