我想问问高度和浮动是如何工作的。我有一个外部的div和一个内部的div,它的内容。它的高度可能会有所不同,这取决于内部div的内容,但似乎我的内部div将溢出其外部div。什么是正确的方法来做到这一点?我的代码如下:

 <html>
    <body>
        <div style=\"margin:0 auto;width: 960px; min-height: 100px; background-color:orange\">
    	    <div style=\"width:500px; height:200px; background-color:black; float:right\"></div>
        </div>
    </body>
</html>

运行结果:

\"css

 

原因解释:

浮动元素不会添加到容器元素的高度,如果您不清除它们,容器高度不会增加...

我会直观地展示给你

\"css

\"css

\"css

更多解释:

<div>
  <div style=\"float: left;\"></div>
  <div style=\"width: 15px;\"></div> <!-- This will shift 
                                        beside the top div. Why? Because the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style=\"clear: both;\"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div\'s 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->
  <div></div>
</div>

你也可以添加overflow: hidden;容器元素,但我建议你使用clear: both;

另外如果你想自己清理一个你可以使用的元素

.self_clear:after {
  content: \"\";
  clear: both;
  display: table;
}
收藏 打印