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!

Build modern and responsive webpages

Responsive Typography

Build modern and responsive webpages Try Front-end

Responsive web design helps your site maintain its design integrity on a variety of screen sizes, but how does it affect your typography? With this practical book, graphic designers, web designers, and front-end developers alike will learn the nuts and bolts of how to get the best appearance from type without sacrificing performance on any device.

$ Check price
24.9924.99Amazon 4.5 logo(3+ reviews)

More Front-end resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad