Protruding CSS inline elements


Published: 2015-12-26
Updated: 2015-12-28
Web: https://fritzthecat-blog.blogspot.com/2015/12/protruding-html-inline-elements.html


This article is about a SPAN element that destroyed my layout, and it took me quite a time to find the explanation for that.

You may know about the fact that there are inline and block elements in HTML, see this page for quick information, and this page for a compound tutorial. In short:

It is illegal to put a block element inside an inline element, so a DIV inside a SPAN is not legal HTML. Although browsers may accept it, they could interpret it differently.

Now there are some side effects when using inline elements. I came across one of them when using a SPAN with some padding and border. Look at the example below:

Parent
Child 1
Child 2

!

The Child 2 SPAN obviously protrudes from its Parent DIV. And it also covers parts of its adjacent Child 1 DIV.

!

Here is the HTML:

  <div id="parent" style="border: 1px solid red; background-color: cyan; margin-left: 20%; margin-right: 20%;">
Parent

<div id="child1" style="border: 0.5em solid green; background-color: yellow;">
Child 1
</div>

<span id="child2" style="border: 1em solid blue; background-color: orange;">
Child 2
</span>

</div>

This happens just

So why is this happening, and how to fix this?
If you want to try a fix, here is a playground. For the distrustful among you I also added the box-sizing property, but actually it does not play any role here.

Child 1 DIV
display:
padding:
em
border:
em
margin:
em
Child 2 SPAN
display:
padding:
em
border:
em
margin:
em
box-sizing:


Parent
Child 1
Child 2


Unfortunately not even the CSS21 specification gave me a clear answer to this problem. I found it here. Solution is (also on stackoverflow):

Inline elements:

So try to set the display: inline property of the Child 2 SPAN in the playground above to inline-block. You will see that the problem is fixed then.

Here is the fixed HTML:

  <div id="parent" style="border: 1px solid red; background-color: cyan; margin-left: 20%; margin-right: 20%;">
Parent

<div id="child1" style="border: 0.5em solid green; background-color: yellow;">
Child 1
</div>

<span id="child2" style="border: 1em solid blue; background-color: orange; display: inline-block;">
Child 2
</span>

</div>

So always put display: inline-block; upon any SPAN that has a border or padding, else it might protrude from its parent, and obscure sibling elements.





ɔ⃝ Fritz Ritzberger, 2015-12-26