SJHwebdesigns

Display

« Previous: Boxes | Next: Positioning and floating »

Maybe you want to apply width and height, and/or vertical margins and padding, to an inline element - or maybe you want to make multiple block-level elements sit side by side rather than taking up a whole line to themselves. You can achieve this by using the display property. This lets you change inline elements to display like block elements, and vice versa.

Applying display: block to an inline element will make it clear a space before and after it, and will allow you to define dimensions, and vertical margin/padding to it - just like a block element. Remember that this is purely presentational - it does not allow you to place block elements within that inline element. For example, applying this to a link:

Code Output
<p>Check out the block-like link:
<a href="#" style="display: block; background: #cf9; margin: 1em; padding: 1em">block-like link!</a>
How cool is that?</p>

Check out the block-like link: block-like link! How cool is that?

Applying display: inline to a block element will disable any dimensions, or vertical margins/padding. The element will then only take up the space occupied by its content. One application of this is creating horizontal lists:

Code Output
<ul>
     <li style="display: inline">Item one</li>
     <li style="display: inline">Item two</li>
     <li style="display: inline">Item three</li>
</ul>
  • Item one
  • Item two
  • Item three

You can also make an element disappear altogether by applying display: none to it. This can allow you to show or hide different elements when the user interacts with the page:

Code Output
a span {
     color: #a00;
     display: none;
     }
a:hover span {
     display: inline;
     }
<p>Can you find the <a href="#">hidden span? <span>hello!</span></a></p>

Can you find the hidden span? hello!

So the <span> only shows up when the user hovers over the link. This is the principle behind many cool CSS effects such as dropdown navigation menus.

Note: the display property has many other possible values; however, block, inline and none are the only ones widely supported by current browsers.

« Previous: Boxes | Next: Positioning and floating »

Page style: Dark Light