Margins and padding
Margins and padding are handy, everyday things in web design, used in everything you'll do. They're not rocket science, but they are similar enough to cause confusion, so you should make sure you understand them up front.
- Margins add space around an element. They increase the space taken up by the element, but do not affect the size of the element itself.
- Padding does 'add space' to the element, effectively making the element itself bigger. If the element has a coloured background, then the padding is coloured too.
The paragraph on the left below has a margin but no padding, and the one on the right has padding but no margin. Both take up the same amount of space. Each paragraph has a yellow background to show its size.
- The one on the left has space added around it, but the size of the element itself (in yellow) is unaffected.
- The one with the padding is effectively enlarged, as shown by the extent of the yellow background.
↑
←This paragraph has a margin on all sides→
↓
This paragraph has padding on all sides
An element can have both padding and a margin.
Specifying margins and padding
You can set the margins and padding for each side individually. You can use either the longhand format, shown on the left below, or the shorthand version on the right (they're identical in meaning). Note the order in the shorthand version: top / right / bottom / left. Several CSS properties have a shorthand version available. Get in the habit of using the shorthand version unless you have reason to do otherwise, as it will shorten your CSS file.
Horizontal centering
Use margins to center a block element horizontally. Do this by entering 'auto' for the left and right margins. You can see this in the example in the boxes below.
Longhand
.classname {
margin-top: 2%;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;
padding-top: 4%;
padding-right: 1%;
padding-bottom: 2%;
padding-left: 0;
}
Shorthand
.classname {
margin: 2% auto 0 auto;
padding: 4% 1% 2% 0;
}