Home and Learn: Web Design Course
You can add space around elements by using some CSS. This is call padding. Here's a centered box without padding:
And here's the same box with some padding:
Let's see how it's done. It's quite easy!
First, here's the CSS and HTML, if you want to duplicate anything here. Copy and paste the following into a blank text file. Save the file as anything.html.
margin: 0 auto;
<h1 align="center">CSS Padding</h1>
Use the shorthand css <span class="TextColor">border-style: solid;</span> to get a solid border.
Load the page in your browser and you should see the squashed blue box from the top of this page.
It's not easy remembering all the different CSS properties, but this one shouldn't cause you too much trouble - it's just padding:
This CSS will add padding to the top, left, right, and bottom of your element. Try it out. Add the line above to your CSS:
margin: 0 auto;
Save and reload the page in your browser. You should see the second blue box at the top of this page and it will have 20 pixels of padding around the text.
Except, the top padding will be bigger, in this case. That's to accommodate the h3 heading we have. In cases like this, it's helpful to control individual padding. You can do this with the following style properties:
The result is this, for the above CSS:
To test it out yourself. Add two forward slashes before the padding line:
(Two forward slashes are the comment symbols for single lines in css.) Add the four lines to your CSS, just below the padding line. Save and reload to see what it looks like in your browser. Now add forward slashes to the other lines. Try the padding properties one by one to get a feel for how they work.
Examine the two blue boxes below:
The first one has had no margin applied. But the second one has had a margin of 100 pixels applied. Notice that in both cases the margins inside the blue boxes haven't changed. And that's the difference between margins and padding: margins are applied to the outside of an element and push the element in the left, right, top, or bottom direction. Padding is applied inside of the element. Here are the various margin properties to try out:
Here's a diagram of the difference:
Incidentally, the sizes don't have to be in pixels (px). You can have them in sizes like em, %, vw, vh, pt, and a whole lot more besides. Mozilla have a good page here that goes into more depths about sizes:
CSS Sizes (opens in new window)
Play around with padding, though, until you get the hang of it. In the next lesson, you'll see how to create a simple one column layout. This will introduce you to the new HTML5 elements.
Email us: enquiry at homeandlearn.co.uk