問題描述
作為一名網絡開發人員,我經常會在另一個(父)div 中放置兩個浮動(子)div.實際上我整天都在這樣做.
As a web developer I frequently will have two floated (child) divs inside of another (parent) div. Actually I do this all day long.
<style type="text/css">
#left {float:left;}
#right {float:right;}
</style>
<div id="parent">
<div id="left" class="child"> </div>
<div id="right" class="child"> </div>
</div>
如果沒有額外的 css/html,這是行不通的,因為父級不會自動增長以適應浮動的子級.有兩種流行的方法可以克服這個問題:
1) 將 overflow:hidden
添加到父級的 css 中.
2) 添加第三個清除"子 <br style="clear:both;"/>
.
This doesn't work without an extra bit of css/html because the parent doesn't automatically grow to fit floated children. There are two popular ways of overcoming that:
1) Add overflow:hidden
to the parent's css.
2) Add a 3rd "clearing" child <br style="clear:both;" />
.
我知道關于這些事情還有其他一些類似的問題,但我的問題是:
I know there's a few other similar questions about such things, but my question is:
哪種方法更好,為什么?什么各有優劣?
Which method is better and why? What are the pros and cons of each?
推薦答案
隱藏溢出 - 非常可靠的方法.主要缺點是如果您在父元素上設置高度,則任何溢出都將......嗯,隱藏.我在創建帶有浮動列表項的菜單時發現了這一點 - 子菜單不會出現.
Hidden overflow - pretty solid method. The main disadvantage is if you set a height on the parent element, any overflow will be...well, hidden. I found this when creating a menu with floated list items - the submenus would not appear.
清除元素 - 而不是換行符,我會使用 height: 0; 的 divclear: both;
因為它不會在下面產生間隙.這是一種更可靠的方法,唯一的缺點是標記中的額外元素.
Clearing element - rather than a line break, I would use a div with height: 0; clear: both;
since it won't create a gap below. This is a more solid method, the only disadvantage being an extra element in the markup.
浮動父元素 - 根據我的經驗,有太多情況您不想浮動父元素,所以我會避免它.
Float the parent - in my experience there are too many situations where you don't want to float the parent element, so I would avoid it.
你也可以使用生成內容的方法:
You can also use the generated content method:
#parent:after {
content: ".";
visibility: hidden;
clear: both;
}
這樣可以節省標記中額外元素的需要,但在 IE7 及更低版本中不起作用.
This saves the need for an extra element in the markup, but it won't work in IE7 and below.
使用內聯塊 - 剛剛記住了這個方法.不要浮動這兩列,而是將它們設置為 display: inline-block
,它們將并排顯示:
Use inline blocks - just remembered this method. Instead of floating the two columns, set them to display: inline-block
and they will appear side-by-side:
.child {
display: inline-block;
vertical-align: top;
}
使用此方法您必須記住的唯一一件事是,如果一個塊的結束標記和另一個塊的開始標記之間有空格,則列之間會出現一個空格(其大小取決于字體,因此很難來衡量).只要你這樣做 ...</div><div id=...
那么這個方法就可以正常工作并且優于浮動元素 IMO.
Only thing you must remember with this method is if there is any whitespace between the close tag of one block and the opening tag of another, a space will appear between the columns (the size of which depends on the font so it difficult to gauge). As long as you do ...</div><div id=...
then this method works fine and is superior to floating elements IMO.
這篇關于浮動子元素:溢出:隱藏或清除:兩者?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!