16 July 2009

The CSS line-height property and how it works

CSS has a line-height property for fonts. I normally use 1.4em for the line-height, as the text sometimes cross at 1em.

Here is a demonstration of the line-height in use:

ZendWeaves CSS Line-Height

First obvious think you'll notice is that line-height only works on block elements and not on inline elements. Secondly, you'll notice that as the font size was set at 10px, the last paragraph at 2em, it's height is 20px. Thus, CSS line-height will vertically center the text automatically for you, which is what I prefer over all the hacks people make to vertically center text.

I find CSS line-height very useful and always set it in my sites. Normally I use 1.4 and sometimes 1.2. Where text won't wrap I might use 1em. By the way, the values can't be negative. If you make the value negative it will default to the normal value. From my testing I don't think incorrect line-height elements will default to the inherit value. Here's the spec:

    Value:       normal |  |  |  | inherit
    Initial:       normal
    Applies to:     all elements
    Inherited:      yes
    Percentages:    refer to the font size of the element itself
    Media:       visual
    Computed value: for  and  the absolute value; otherwise as specified

On a block-level, table-cell, table-caption or inline-block element whose content is composed of inline-level elements, 'line-height' specifies the minimal height of line boxes within the element. The minimum height consists of a minimum height above the block's baseline and a minimum depth below it, exactly as if each line box starts with a zero-width inline box with the block's font and line height properties (what TEX calls a "strut").

On an inline-level element, 'line-height' specifies the height that is used in the calculation of the line box height (except for inline replaced elements, where the height of the box is given by the 'height' property).

Values for this property have the following meanings:

    Tells user agents to set the used value to a "reasonable" value based on the font of the element. The value has the same meaning as . We recommend a used value for 'normal' between 1.0 to 1.2. The computed value is 'normal'. 

    The specified length is used in the calculation of the line box height. Negative values are illegal. 

    The used value of the property is this number multiplied by the element's font size. Negative values are illegal. The computed value is the same as the specified value. 

    The computed value of the property is this percentage multiplied by the element's computed font size. Negative values are illegal. 

Take care!


No comments:

Post a Comment