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

◇◆丶佛笑我妖孽 提交于 2019-12-21 04:50:59

问题


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.

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?

Below is an example:

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.


回答1:


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

Demo


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

For example

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



回答2:


adding a clear:both; in the 3rd child helps:

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



回答3:


You have to use the clear property.

For your example:

.child:nth-child(3) {
    clear: both;
}

In jsfiddle.



来源:https://stackoverflow.com/questions/20102120/html-css-clear-floating-elements-in-the-middle-without-adding-unneeded-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!