HTML/CSS : Clear floating elements in the middle without adding unneeded tags

标签 html css css-float clearfix

<分区>

大多数 clearfix 技术都涉及在父容器的最底部添加内容,我最喜欢伪元素方法,因为它不会将不需要的元素添加到 HTML 中。

但是,最近我发现我正在处理一个有一些 child 漂浮但不是全部漂浮的容器。假设前两个 child 第一个向左漂浮,第二个向右漂浮。我需要一种方法来清除第二个元素之后的 float ,这样下面的内容就不会被挤在它们之间。有没有办法在不添加clearfix元素的情况下清除中间的 float 元素?

下面是一个例子:

HTML

<div class="container">
    <div class="child">
        first child!
    </div>
    <div class="child">
        second child!
    </div>
    <div class="child">
        third child!
    </div>      
</div>

CSS

.container {
    width: 200px;
}

.child:nth-child(1) {
    float: left;
    background: yellow;
}

.child:nth-child(2) {
    float: right;
    background: red;
}

.child:nth-child(3) {
    background: blue;
    color: white;
}

请看这个jsfiddle看看我现在有什么。

最佳答案

只需使用 clear: both;在第 3 个 rd 元素上,这样你就不必使用 <div style="clear: both;"></div>在 float 元素之后。

.child:nth-child(3) {
    background: blue;
    color: white;
    clear: both;
}

Demo


此外,如果您希望在不添加额外元素或不使用 overflow: hidden; 的情况下清除父元素这是一种肮脏的方式 clear花车,你可以调用class在父元素上,具有以下属性

.clear:after {
   content: "";
   display: table;
   clear: both;
}

例如

<div class="wrapper clear">
    <div class="left_floated_div"></div>
    <div class="right_floated_div"></div>
</div>

关于HTML/CSS : Clear floating elements in the middle without adding unneeded tags,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102120/

相关文章:

javascript - Onclick 在 div 之外隐藏 div

height - 正确清除 float <li>

html - CSS float 不能正确定位 <div>

html - 水平对齐的 div 在 Chrome 中工作,但在 Firefox 中不工作

使用解析器进行 Javascript 搜索

HTML Force 引入断行/换行

javascript - 使用 jquery 切换对象的类

javascript - 如何在 Javascript 乒乓球游戏中正确地偏转球?

javascript - 创建多按钮唯一点击计数器

jquery - 在某些 HTML 标记后停止打印