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

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Ad