CSS Layout and floats

In which we find out how to align things relative to each other.

About widths and padding

See this page about the CSS box model

You'll see that width (and height too) refer to the width of the content, not the outside width of the container (or other box).

One approach to let you specify things in terms of the size of the containing box, rather than the content, is to nest two divs, like this:

<div class='outerbox'>
  <div class='pillow'>
    <p>Here's my content...</p>
  </div><!--end pillow div-->
</div><!--end outerbox div-->

With styles like this:

outerbox{
  margin: 0px; 
  padding: 0px;
  width: 600px;
}
pillow{
  margin: 30px;
}

Further subdividing the container - vertically

See that alistapart article on HTML 5 for suggested divisions of header, footer, nav.

Context sensitive selector

A selector with a space in the middle, like this:

#nav ul{
  display:inline;
  padding-left: 10px;
  padding-right: 5px;
}

means: if you find a <ul> inside a <div id='nav'> division, apply this style...

See also: "Taming lists".

Float

The style that allows you to line up boxes beside other boxes is:

float: left; /* this box moves left */

...or float: right; to move a box right, while the remaining content wraps around the image, if possible, on the other side.

Clear

.wrapnomore{clear: both}

Content wrapping will stop at the next tag after a floated box with this style set. For example:

<p><img src='somepicture.jpg' alt='picture description' 
  class='floatleft'>A bit of text</p> 
<h4 class='wrapnomore'>The next headline</h4>

without clearing

Don QA bit of text

The next headline

Aack! That floated image has even escaped its <div>! Better quick insert a...
<br class='wrapnomore' />

with clearing

Don QA bit of text

The next headline

Columns

...are floated <div> boxes. It's often a good idea to set widths on these in percentages, which works whether your container has a fixed width or is flexible.