CSS inline/block nuances
When you set an element to
display:inline-block; browsers treat HTML whitespace adjacent to the styled element as though it were content.
At first this confused me, and I assumed the implementation in Safari and Firefox was buggy. The weird gaps either side of elements set to
display:inline-block; have annoyed me for a while . Normally whitespace outside of an HTML element has no effect on how it’s displayed, and even inside an element (except <pre>) whitespace collapses to a single character even if there are multiple characters in the code. Except here. The following code blocks produce differing results.
<ul> <li>one</li> <li>two</li> <li>three</li> </ul>
When we set the list item to
display:block both code examples render a list where each item appears one under the other. When we use
display:inline , there is a display difference between the code examples. They are both laid out horizontally, but the first example has whitespace between each item: it reads “one two three”, the second has no whitespace and reads “onetwothree”.
That’s odd behaviour for HTML, but it sort-of makes sense in context of the definition for the property. It’s aiming to make the styled element behave as though it was inline, whilst rendering as though it’s a block. It’s trying to make a “block” part of a sentence. It treats the block as though it was a word, and puts spaces either side if there are spaces either side of the element in the code.
Frankly, I hate this behaviour. It means if I format my code so it’s readable I end up with spaces either side of an element. That’s dumb. If I want a space either side I can set a margin on that element. However with the behaviour it has now, I can not remove the spaces using CSS without refactoring the whitespace around the HTML element in the source code. This was driving me insane at work.