2014-03-02 27 views
1

我最近遇到了問題,當我試圖不使用我的CSS文件中的浮動規則。CSS,我不想要一個元素浮動

我看到了問題,當我的div元素的其他分配的CSS規則沒有浮動沒有工作。

任何人都可以告訴我什麼CSS規則我應該使用,而不是浮動當我想要它開始一個「新行」,但不是浮動?

例子:

.element1 {width:100%;float:left;margin:20px 0;} 
.element2 {width:90%;margin:20px 0;} 

如果我不使用浮動分配element2,它忽略了保證金聲明。

+0

您是否考慮過'inline-block'? –

回答

4

使用清除屬性。

.element2 {clear:both;} //options are: both, left, right 

如果不夠,您可能需要添加一個div到'clearfix'中斷處。 看看這種技術:http://nicolasgallagher.com/micro-clearfix-hack/

/** 
* For modern browsers 
* 1. The space content is one way to avoid an Opera bug when the 
* contenteditable attribute is included anywhere else in the document. 
* Otherwise it causes space to appear at the top and bottom of elements 
* that are clearfixed. 
* 2. The use of `table` rather than `block` is only necessary if using 
* `:before` to contain the top-margins of child elements. 
*/ 
.cf:before, 
.cf:after { 
    content: " "; /* 1 */ 
    display: table; /* 2 */ 
} 

.cf:after { 
    clear: both; 
} 

/** 
* For IE 6/7 only 
* Include this rule to trigger hasLayout and contain floats. 
*/ 
.cf { 
    *zoom: 1; 
} 

你會使用這樣的:

<div class="element1"></div>//floats 
<div class="cf"></div> 
<div class="element2"></div>//new line, responds to margin, etc perfectly 
+0

試過了,它仍然忽略了保證金聲明。 – Jack

+0

然後你需要一個clearfix。看看:http://nicolasgallagher.com/micro-clearfix-hack/ – enapupe

+0

感謝您的幫助;)<3 – Jack

1

clear:both應該做的魔力:

CSS

.element1 {width:100%;float:left;margin:20px 0;} 
.element2 {width:90%;margin:20px 0;} 
.clear {clear:both;} 

HTML

<div class="element1">a</div> 
<div class="clear"></div> 
<div class="element2">b</div> 
+0

你是對的,它做了魔術,lova你! ;) – Jack