HTML / CSS:在中间清除浮动元素,而不添加不必要的标签 [英] HTML/CSS: Clear floating elements in the middle without adding unneeded tags

查看:223
本文介绍了HTML / CSS:在中间清除浮动元素,而不添加不必要的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数clearfix技术包括在父容器的最底部添加东西,我更喜欢伪元素方法,因为它不会在HTML中添加不必要的元素。

Most of the clearfix techniques out there involves adding things at the very bottom of the parent container, and I prefer the pseudo element approach the most since it doesn't add unneeded elements into the HTML.

然而,最近我发现我处理的容器有一些儿童浮动,但不是所有。说前两个孩子,第一次漂浮,剩下的第二次漂浮。我需要一种方法,在第二个元素之后清除浮动,所以下面的内容不会被挤压在它们之间。有没有办法清除中间浮动元素,但没有添加clearfix元素?

However, recently I found that I am dealing with a container that has some children floating but not all. Say the first 2 children the first floats left and the second floats right. I need a way to clear the float right after the second element, so the content below doesn't get squeezed in between them. Is there a way to clear floating elements in the middle but without adding clearfix element?

下面是一个示例:

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;
}

请参阅

Please see this jsfiddle to see what I have right now.

推荐答案

只要使用 / d> code> clear:both; 在3 rd 元素上,这样就不必使用< div style =

Just use clear: both; on the 3rd element, this way you don't have to use <div style="clear: both;"></div> after the floated elements.

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

演示

此外,如果您希望清除没有添加额外元素或使用 overflow:hidden; 这是脏方式清除浮动的父元素可以在父元素上调用

Also, if whenever you are looking to clear a parent element without adding an extra element or using overflow: hidden; which is a dirty way to clear floats, you can call a class on the parent element, with the properties below

.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:在中间清除浮动元素,而不添加不必要的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆