Anthony Martin
Anthony Martin

Reputation: 678

Varying line-height and font-size causing gaps in inline-block elements

I'm putting a simple navigation bar together. Initially I just wanted all of the links to be centered vertically, so I used the following CSS, which did what I needed:

.link {
    display: inline-block;
    line-height: 3em;
    height: 3em;
}

I then wanted some of my links to be in a larger font size. I did this by setting the line-height and font-size property differently on each element, however I made sure that the line height would be calculated as 3em respective to the parent:

.link1 {
    display: inline-block;
    font-size: 1.5em;
    line-height: 2em;
}
.link2 {
    display: inline-block;
    font-size: 2em;
    line-height: 1.5em;
}

In doing this, I noticed that there were small bands above and below the elements where the elements were being vertically offset slightly.

I've created a JSFiddle here to demonstrate the issue. I suspect that I could hack around this issue with a float: left and a clearfix, but I would like to hear the 'correct' way to solve it.

To summarise, all I'm trying to achieve here is divs with the same height but different font sizes, and with the text vertically centered.

Thanks very much for your help.

Upvotes: 2

Views: 1192

Answers (1)

CupawnTae
CupawnTae

Reputation: 14580

The line-heights of the spans are equal, but by default they are vertically aligning on the baseline of the text. Since the text is vertically centred in the spans, the baseline of the smaller text is higher in the span. So when the baselines are aligned, the tops of the spans with the smaller font are lower than the tops of the other spans.

You can vertically centre the spans using vertical-align: middle (or top or bottom, basically anything other than the default baseline) if you don't mind your text actually being vertically centred. This gives you what you're looking for, although it may seem like the smaller text is "floating" a little due the the baselines not being aligned any more.

(Also note that the height properties are having no effect on the spans).

Upvotes: 3

Related Questions