Watkins Web 3: Blog

Cheat Sheet: Inline vs. Block Revew

Related to the box model is the distinction between block-level elements and inline elements.

Block-level elements (e.g. p, h1 through h6, ul, li) take up their own horizontal line and expand to fill the space available to them. For example, if you have a short heading (like <h3>My Skills</h3>) and apply a border-bottom to it, that border will extend well past the end of the word and won’t stop until it hits the edge of the containing element (your div or article or whatever).

Inline elements (e.g. a, img, span, strong, em, input) are part of the natural flow of running text and don’t take up their own lines by default (think of how you can wrap a phrase with the <strong> tag and it won’t push anything to the next line). These elements also don’t always respond to margin and padding as you might expect.

Now for the important part: you can change the behavior of any element using the display property.

Use display: block; to force an inline element to behave like a block-level element:

nav li a {display:block;} /* force the clickable link to expand to the full width of the list item */

Use display: inline; to force a block-level element to behave like an inline element:

nav ul li {display:inline;} /* force the li's to sit on the same line as each other */

There’s one more option: display:inline-block forces an element to acquire a sort of mixture of the two properties: the element will be inline in the sense that it will follow the flow of running text and sit side by side with adjacent content (also, borders will surround only the text itself, not the whole link). But it will be block in the way it reacts to width, height, margin, and padding:

nav li a {display:inline-block; border:1px solid blue; padding:3px; margin-right:20px;} /* put nav items in a row but allow block-like properties to be applied */

Keep in mind that display:inline-block has weak support in IE7 and lower.