CSS clearfix not working

别来无恙 提交于 2021-02-05 06:16:06

问题


This (http://jsfiddle.net/77RRA/1/) is working, while this (http://jsfiddle.net/77RRA/) is not.

Isn't clearfix supposed to substitute the line <div style="clear: both;"></div>?


回答1:


Isn't clearfix supposed to substitute the line <div style="clear: both;"></div>

Yes. The clearfix is there to avoid a non-semantic empty tag. However, for this to work you need to place it on the parent element. (Example)

In your case however, it does not address the problem that siblings will ignore the floated element. This is not the intend of clearfix, you simply add clear:right (or both as you will) on your #child sibling to restore the normal document flow.

your fixed Example




回答2:


"Isn't clearfix supposed to substitute the line <div style="clear: both;"></div>?"

  • No

Imagine you have a container holding several items. If all of those items are floating, the container effectively loses its information of height. So margin-bottoms and background-styles are being displayed wrong. The clearfix solves this problem by adding pseudo-elements before and after the container element + setting a display: table; to stretch it back to its full height.

In your case, you will have to add a clear: both; on #child




回答3:


In your case , you are trying to clear floatting element from itself (with a pseudo-element that belongs to itself).

Clear should be on elements following floatting elements.

Some other rules can achieve this too.

http://jsfiddle.net/77RRA/6/

#main {
    background: lightgreen;
    width: 100px;
    height: 200px;
}

#one {
    float: right;
    display: block;
}

#child {
    background: red;
    width: 100%;
    height: 20px;
    display:inline-block
}

display:inline-block; will clear this element from floatting elements any sides.



来源:https://stackoverflow.com/questions/17109563/css-clearfix-not-working

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