开发者

Using ::after to self clear divs. Is this working right?

I have the following HTML:

<div class="selfClear" style="float: left; border: 1px solid black;">
      ...floated stuff in here...
</div>
<span style="margin-top: 10px; border: 1px solid purple;">hello world</span>

I'd like there to be a 10px gap between the div and span, per the margin-top. But, since the div above is floated, it won't render that way. The fix to make sure something clear's the DIV. To do that via pure CSS, it appears one should use the '::after' method of开发者_运维技巧 inserting content that is then set to clear:

.selfClear::after {
content: ".";
display: block;
height: 0px;
clear: both;
visibility: hidden;
}   
.selfClear {
    display: inline-block;
}

However, this doesn't quite do what I think it should be doing. If I don't include the height/visibility styles so that I can actually see the period as it is inserted, I see that it's actually rendering inside the div (the black border encloses it), rather than after the div (so it's between the div and span). Am I misunderstanding how this should be working?

EDIT:

Here's a simpler example:

CSS:

#theDiv {
border: 1px solid green;
}

#theDiv::after {
content: ".";
}   

#theOtherDiv {
border: 1px solid orange;
}

HTML:

<div id="theDiv">
    Hello
</div>
<div id="theOtherDiv">
   World
</div>

That ends up placing a period after 'Hello' rather than after the div.

It appears that ::after and ::before are actually appended to the CONTENTS of the element, not the element itself. Is that correct?


Yes, it appends to the content of the selected element. You could try wrapping the div then appending after the wrapper div, but that defeats the whole purpose of using :after in the first place.


You could also try setting the enclosing div to 'overflow: auto'. That works everywhere.


I would suggest using clearfix - it's a lot simpler, you just set up a surronding with a class of clearfix.

See this example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜