Margin & Padding in CSS
Lessons Covered


In the previous lesson you learnt about the box model. The box model provided the layout of the margin and padding. In this lesson we will discuss each of these.



The Pading

If you recall, the padding surrounded the content. The padding gives some space around this area based on your specifications. It is the diatance between the border and the content itself.

The values of padding can be specified in pixels or even as a percentage.


The example below shows how exactly the padding could be represented in a style sheet:

style.css

body
{
padding: 20px;  <----- padding set to 20 pixels
}


By setting the padding to a value of 20px, it is applied all around. This means the top, bottom, left and right will have a 20 pixel padding.


You can of course set individual paddings like this:

style.css

body
{
padding-top: 20px;    <----- Sets the top padding
padding-right: 30px;  <----- Sets the right padding
padding-bottom: 25px; <----- Sets the bottom padding
padding-left: 30px;   <----- Sets the left padding
}



There is also a short format of setting all the paddings in only one line. This is how it's done:

style.css

body
{
padding: 20px 30px 25px 30px; <----- Sets the top, right, bottom and left paddings 
                                      respectively
}


Using this method, we accomplish applying the same paddings specified in the example before this one. It has to be done in a clock wise fashion. The first value represents the top padding, the second value represents the right padding, the thrid represents the bottom padding and the fourth, the left padding.


The Margin

In the box model, the margin was outside the border. It clears this area based on your specifiation.

Just like the padding, the values that can be specified in pixels or even as a percentage.


Below is an example of the margin applied in a style sheet:

style.css

body
{
margin: 10px;  <----- margin set to 10 pixels
}


Just like when applying the padding you can also define margins individually:

style.css

body
{
margin-top: 10px;
margin-right: 20px;
margin-bottom: 15px;
margin-left: 20px; 
}


Margins can also be specified in one line:

style.css

body
{
margin: 10px 20px 15px 20px;
}




Simple right ? By using margin and padding you have control over the layout. It can accomplish some pretty useful things. Let's move on to the next CSS lesson.


    Previous Lesson Previous Lesson - The Box Model                            Next Lesson - Floating Next Lesson