03. Applying Padding and Margin

Padding

To apply a padding, use the padding-top,padding-right,padding-bottom, andpadding-leftproperties.

#sample {
  padding-top: 10px;
  padding-right: 12px;
  padding-bottom: 10px;
  padding-left: 12px;
} 

We can use the shorthand padding to group these values together. This way, we can specify the top, right, bottom, left in one go!

The following code specifies the top, right, bottom and left paddings, respectively.

#sample {
  padding: 10px 12px 10px 12px;
} 

If we only specified two values, the first value specifies the top and bottom values, while the second value sepcifies the left and right values.

#sample {
  padding: 10px 12px;
} 

We can also place three values, which will specify the top, left and right, and bottom.

#sample {
  padding: 10px 12px 10px;
} 

Thus, all the above examples would give a box similar to this:

Content area

Notice the area in between the content and its border - that's the padding being applied.

Without the padding, here's what it would look like:

Content area

Using shorthand notations

Try to memorize the following, as they'll apply to properties other than just padding.

4 values
Top, left, bottom, right (clockwise).
3 values
Top, left-right, bottom.
2 values
Top-bottom, left-right.

Margin

Just like padding, we can specify: margin-top, margin-right, margin-bottom, and margin-left.

We can also use the shorthand notation margin to specify all these in one go.

Centering an element

To horizontally center an element relative to its parent container, specify auto as the left and right margin values.

div #sample {
  padding: 10px 12px 10px;
  margin: 40px auto;
} 
Content area

Notice all that area around the border. That's the margin!

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Build modern and responsive webpages

HTML & CSS

Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Ad