Aug 24th
2010

CSS: Where’s My Vertical Margin?

Let’s chat today about a CSS bugger that has probably thrown us all off once or twice. I’m talking about vertical margin (top or bottom) on inline elements. If you haven’t discovered this yet, they don’t work. But before we get into the details of this, let’s get a refresher on Block elements vs. Inline elements.

Block elements, by nature, are items like, <div>, <p>, <ul>, all the <h*> tags, etc. These will stack on top of each other when placed one after the other in the flow of your HTML. You can think of them as having a built in <br> tag. All of these block elements have margin and padding that apply on all edges.

Inline elements, by nature, are items like <span>, <a>, <em>, <strong>, etc. These items will line up next to each other when placed one after the other in the flow of your HTML. They will wrap when they reach the edge of their containing <div>. These have a margin and padding that apply only on the left and right. So, now that we have that little bit of knowledge let’s talk about why, when we try to add a vertical margin or padding to our inline elements, it doesn’t take.

The reason is: the height property does not affect inline elements. If top or bottom margins are set, they will have no visual effect, as margins do not affect the line-height calculations. Ah, that’s why!

So when you’re dealing with a chunk of code like so:

<span class=”giddy”>This is a span tag, it is an inline element.</span>
<span class=”up”>This is another span tag, yet another inline element.</span>

and you want to vertically space these two elements vertically. You could do this:

<span class=”giddy”>This is a span tag, it is an inline element.</span>
<br />
<br />
<span class=”up”>This is another span tag, yet another inline element.</span>

But that’s ugly and wasteful. Instead you should modify your CSS changing these <span> elements from inline, into block. Now, the block elements listed above essentially have a display: block; automatically assigned to them as interpreted by the browser, even if it’s not explicitly stated in your CSS, it is there. (Technically, you could simply change out the <span> tag for a <div> tag and you’d be done.) Same goes for inline elements, however instead of display: block;, it’s display: inline;. So in order to give our little <span> tags some vertical spacing, we need to override the display: inline; with a display: block; in our CSS. That would look something like this:

span.giddy, span.up {
display: block;
margin: 4px 0;

Now we have changed our <span> into a block element, and the top and bottom margin of 4px that we have applied should take effect.

There are many other uses for converting inline elements to block elements that really show the flexibility and power of CSS. Try experimenting with reducing your markup by getting more creative with the properties you’re applying to your elements.

Next Post → ← Previous Post