Last week I discovered a pretty novel way of created a CSS grid layout. After living with this layout for a week, I revisit some of the pitfalls it has caused.
The Bane of inline-block#
The pitfalls of using inline-block for layout have been well documented over the years, however it seems I’m slow to learn. So just as a reminder to myself, I’m going to go over the reasons why using inline-block for layout is a bad idea and should be avoided.
The 4px of Pain#
This issue is the first argument against using inline-block for layout. Two inline-blocks placed beside each other don’t touch edge to edge. This is because the inline-blocks are treated as words, and words, as well as letters, have spaces between each other.
Because of this issue, if we set each block to
width: 25%; , they wrap to the next line, like this:
This issue can be alleviated by setting
word-spacing: -4px; like so:
Problem solved right? Wrong.
word-spacing property is dependent on the font your using. Watch what happens when we set ‘Helvetica’ as the font-family of our body:
Our boxes are broken again.
This is because every single font has it’s own word spacing and letter spacing, and it’s not necessarily 4px.
This reason alone should be reason enough to stay away from inline-block for layout purposes, but there is one more reason.
At The Mercy of White Space#
Inline-blocks depend on white space to separate elements. Just as words are separated by spaces, so are inline-blocks. The pitfalls of this are not obvious at first, so let’s take a look at what happens when we remove the whitespace between our inline-blocks (click on ‘result’ to see the difference).
Our layout becomes totally broken. Now you might be thinking, “In that case, I’ll just add white space to my HTML and problem solved”. Not quite.
Even if you add white-space to your HTML, it will be removed in a few important circumstances:
Your Minifying your HTML - If you minify your HTML in your build or deploy process, all the white-space will be removed, potentially breaking your layout.
Your manipulate the DOM in any way - If you touch the DOM in any way, for example to AJAX in content, that content will be inserted without white-space. This can be a big issue in applications where there is a lot of dynamic content. The following jQuery code for example, will append 2 inline-block elements, but will do so without the whitespace between them:
$('<div class="inline-block"></div> <div class="inline-block"></div>').appendTo('body');
This second reason can be a real pain to solve if your application depends heavily on dynamic content, or if you’re using libraries that do a lot of DOM manipulation, such as Angular, it could be almost impossible to solve.
Inline-block for layout… just don’t do it.