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

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

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

More Front-end resources

Ad