|
|
CSS Padding, Margin and Border
Padding, Margin and Border (The Box Model)
All content in CSS is displayed using a model called "the box model". Essentially, this means that each element on a page is a box, which has a width and height and cannot overlap with other elements. There can, however, be "dead" space between elements which does not have an element taking up its space. The box model is one of the things that confuses people the most when they start specifying layouts with CSS, so we want to take a different approach to the explanation. Instead of explaining padding, margins and borders separately and then demonstrating how they go together, we are going to show you the box model as a whole, and then go into the different parts afterward.
The box model is constructed in four parts: the content itself, the padding for the content, the border and the margin from the border to the edge of the box. This image should explain this more clearly: ![]()
Setting up your border
You can add a border easily in CSS - using the
border property. You can also set different borders for each side using the border-top, border-right, border-bottom and border-left properties. Border definitions have three parts - the width, the style and the color. Here's some examples:
p.border1{ border: 1px solid red; }
p.border2{
border-top: 2px dotted green;
border-right: 10px groove #0000FF;
border-bottom: 15px inset rgb(255,0,0);
border-left: 6px double #333333;
}
Example 1 Example 2
The three dimensional borders (groove, ridge, inset and outset) only really work if all of the borders are the same type - they also are quite difficult to get to look good so be careful when using these.
Margin and Padding
Margins and padding work in the same way as each other (but affect different parts of the box as in the image above). You specify the padding and margin in sizes as with
font-size (pixels, percentages, em), and margin can also take the value of auto, which will expand the margin evenly on each side to the elements around it. Specifying the padding and margin is easy:
p{
padding: 0px 10px 5px 0px;
margin: 0px 0px 1px 0px;
}
These are specified in "shorthand" where the values represent the sides clockwise from the top (top, right, bottom, left). You can also use
-top, -right, -bottom and -left with margin and padding the same was you can with border as we demonstrated above.As we mentioned, the box model can be confusing at first, but we hope that by explaining how the boxes work and then telling you how to specify the different parts we've removed some of the confusion. Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|