问题
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