子div用了float浮動之后,如何撐開父元素,讓父元素div自動適應高度的問題


方法一:

html:

<div id="all1">

<div id="left1">1</div>

<div id="left2">1</div>

<div style=" clear:both; "></div>

</div>

css:

#left1{ float:left;width:200px;}

#left2{ float:left;width:200px;}

#all1{}

這個方法的關鍵在於用了clear:both來清除了浮動元素,把父元素all1撐開。

方法二:

html:

<div class="aa">
  <div class="bb">sffsssssssssssss</div>
  <div class="cc">sffss</div>
</div>

css:

.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}
.bb { border:1px solid #f00; background:#999; float:left;}
.cc{ border:1px solid #f00; background:#999; float:left;}

此方法的重點在於,子元素有float之后,父元素需要設置一個overflow:hidden;,這樣就可以自動撐開父元素aa。

 

特別注釋:

 

overflow:hidden要有寬度或者高度才會溢出部分隱藏,如果外部盒子沒有寬度或者高度,里面又是浮動元素,就會被撐開

 

總結如上的方法,各有適合的地方。比如overflow:hidden之后,超出父元素位置的子元素就看不到了,可以試一下如下的兩段代碼對比一下,

代碼一:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<style type="text/css" >
.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}
.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}
.cc{ border:1px solid #f00; background:#999; float:left;}
</style>
<body>
<div class="aa">
  <div class="bb">圖片</div>
  <div class="cc">圖片</div>
</div>
</body>
</html>

 

效果圖:

代碼二:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<style type="text/css" >
.aa{ border:1px solid #000; background:#CC4;}
.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}
.cc{ border:1px solid #f00; background:#999; float:left;}
</style>
<body>
<div class="aa">
  <div class="bb">圖片</div>
  <div class="cc">圖片</div>
<div style="clear:both"></div>
</div>
</body>
</html>

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM