Advanced CSS Layout

In the examples on the previous page we set even padding, borders, and margins on all sides of our HTML elements. Now let's see how we can specify different values for each side of our box, to give us an even greater level of control over our styling.

We can specify individual values for our padding, borders, and margin by adding the suffixes -left, -right, -top or -bottom to our style declarations. For example, the following code would add a 1px solid black line underneath any text we specified as emphasized <em>:

em {
	border-bottom: 1px solid black;
	}

Note also that these more specific style declarations will over-ride any more general ones. For example, say we wanted a margin of 1em on the top, right and bottom of each of our HTML <img> elements, but only 0.5em on the left. Rather than specifying each one individually we can start by declaring a 1em margin all round and then setting our more specific left margin:

img {
	margin: 1em;
	margin-left: 0.5em;
	}

We can also use shorthand to specify each side individually in one line. The order goes top, right, bottom, left:

img {
	margin: 1em, 1em, 1em, 0.5em;
	}

We can apply this exact same process to our element padding, giving us complete control over exactly how HTML elements are positioned and spaced.

Before we finish discussing the Box Model let's take a look at a couple of cool things we can do with the border property on the next page.