SEARCH !!

2010/03/01

如何修正DIV 指定float之後導致外容器無法撐開

初碼:
<div style="border: 1px solid red; width:120px;">
<div style="border: 1px solid green; float: left; width: 30%; height: 80px;">DIV1</div>

<div style="border: 1px solid blue; float: right; width: 60%; height: 80px;">DIV2</div>
</div>

想做出如下的效果

卻因為在子層DIV下了float 造成中外容器無法撐開的狀況,如下


法1:
<div style="border: 1px solid red; width:120px;">
<div style="border: 1px solid green; float: left; width: 30%; height: 80px;">DIV1</div>
<div style="border: 1px solid blue; float: right; width: 60%; height: 80px;">DIV2</div>
<div style=”clear:both”></div> <---多加這有clear:both;的DIV,由他去撐開 
</div>

缺點是多了沒必要的DIV,且也許會在下程式時產生影響 

法2:
利用CSS增加子元素,但IE7之前不支援 (clearfix 為外容器ID)
 #clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

 forIE6,7?
#clearfix { zoom: 1; }

Imagine that we use :after to insert a simple character like a 'period',
and then give that generated element {clear: both;} .
That's all you really need to do the job,
but no one wants a line space messing up the end of their clean container box,
so we also use {height: 0;} and {visibility: hidden;} to keep our period from showing.
Notice that {display: block;} is also applied to the :after element,
because if it isn't then that element defaults to "inline",
and cannot receive the "clear" property. Also,
Tony's method originally used "overflow: hidden;" to hide the period,
but sadly the latest FireFox versions will display the period if this is done.

----------------------------------------------------
http://www.positioniseverything.net/easyclearing.html


----------------------------------------------------------------------------------------
法3:

在付容器直接加上

.父容器 {
  border : 1px solid #F00;
  overflow : auto; /* IE7 IE8 Firefox Chrome Safari */
  _width : 100%;  /* IE6 */
}

overflow 的值可以更改為 hidden 、 scroll 。
 _width : 100% 如果有後遺症的話,也可以試試 _height : 1% 。
IE6 和 IE7 .float 最下面的 margin-bottom 會被吃掉,可以考慮在 .pool 加上 *padding-bottom 修飾。

沒有留言:

張貼留言