开发者

CSS display issue where border applied to div is stretching around other elements

I have an issue where the css border applied to a div element is stretching around the span tag directly above it (a span tag which is NOT within the div tag). Now, I already have a workaround for this which can be found in the following example but I would still like to know why this is happening:

<html>
<head></head>

<body>
<span style="float: left;">(Floated Span)</span>
<div style="border: 1px solid black;">
    This is the only text which should have a border around it.
</div>
<span style="float: left;">(Floated Span)</span>
<br />

<br />
I do NOT expect the border from the div tag to stretch around the floated span, but it does.
<br />
Therefore, I would expect the floated span below the div tag to do the same, but it doesn't.
<br />
Happens in FF and IE.
<br />
<br />

<span style="float: left;">(Floated Span)</span>
<br />

<div 开发者_运维问答style="border: 1px solid black;">
    This is the only text which should have a border around it.
</div>

<span style="float: left;">(Floated Span)</span>
<br />

<br />
Apparently BR tags are magical and solve the problem for whatever reason.
<br />
Works in FF and IE.
<br />

<br />
<span>(Span)</span>
<span style="float: left;">(Floated Span)</span>

<div style="border: 1px solid black;">
    This is the only text which should have a border around it.
</div>

<span style="float: left;">(Floated Span)</span>
<br />

<br />
If an unstyled span is added before the floated span, Firefox displays the content the way I expect.
<br />
However, IE still decides to stretch the border from the div tag around the floated span.
<br />

<br />
<span style="float: left;">(Floated Span)</span>    
<span>(Span)</span>

<div style="border: 1px solid black;">
    This is the only text which should have a border around it.
</div>

<span style="float: left;">(Floated Span)</span>

<br />

<br />
Switching the order of the floated span and unstyled span in the code 'fixes' the previous issue with IE.
</p>
</body>
</html>


See block formatting contexts on w3.org.

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats)


It looks like this is happening because the spans are being floated.

This means they are taken out of the document flow.

The div underneath them then pushes up, and if transparent, would look like it "includes" the span.


If you add a 'clear: left' to the div below the span it will fix this issue.

This issue is because of the span being floated and the div doesn't clear anything out of the way before rendering so the span floats over the div below.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜