Blog-Archiv

Samstag, 26. Dezember 2015

Protruding CSS inline elements

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:

  • inline elements (like SPAN) flow horizontally, like text, next to each other
  • block elements (like DIV) flow vertically, they start a new line and cover the whole width

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

  • on top and bottom of the element, not left or right of it
  • when there is a padding, or a border, or both
  • with inline elements like SPAN

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:
  • respect left and right margin / padding / border, but not top and bottom
  • cannot have a width and height

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.




Keine Kommentare: