CSS,我不想要一个元素浮动

时间:2014-03-02 13:05:58

标签: html css

当我尝试不在我的css文件中使用浮动规则时,我最近遇到了问题。

当我的div元素的其他指定的css规则没有浮动时,我看到了问题。

任何人都可以告诉我,当我希望它开始一个“新行”而不是浮动时,我应该使用什么css规则而不是浮动?

示例:

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

如果我没有为element2指定浮点数,它会忽略保证金声明。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>