Skip to content

CSS Lesson 6: Shorthand Properties (Padding and Margin)

by Brad on January 25th, 2010

The padding and margin CSS properties are essential in building web layouts.  Since rectangles (block level elements) have four corners, you will frequently need to assign four different padding properties to one element.  If you are a beginner, this is the code you would likely use:

#header {
    padding-top: 10px;
    padding-right: 15px;
    padding-bottom: 6px;
    padding-left: 15px;
}

However, there is a much more efficient (not to mention easier!) way of applying four padding or margin values. Here is your first glimpse of CSS Shorthand in action; the following code achieves the same exact results as the padding example I just provided:

CSS Shorthand graph

You simply list four values, one directly after the other, and the web browser interprets this as the four (clockwise- top, right, bottom, left) directional values.

Similarly, you can also list two values in a row and the browser will interpret the first to be both top and bottom, and the second value to be both left and right.

CSS Shorthand graph 2

Using this new knowledge, let’s imagine we need to add 10 pixels of right margin and 15 pixels of bottom margin to an element. Here’s the code we would use:

#header {
    margin: 0 10px 15px 0;
}

We used the four-value shorthand syntax, and simply included zeroes for the directions (top and left) we didn’t want to apply margin to.

That’s it for today’s lesson. Hopefully your CSS code will be a little cleaner with these simple shorthand methods.

From → CSS Lessons

6 Comments
  1. Very good tutorials. Thank you. You make things easy.

    Seems like you fixed the issue for the syntax highlighter. So did substituting the css elements do the trick for you?

    Keep up the good work. I would be following you!

    Cheers

  2. Brad permalink

    Hi Pali, thank you for the kind words!

    Regarding the syntax highlighter, I had referenced the “code” and “pre” elements in my theme’s CSS file (before finding the great plugin). When I removed these CSS rules, and let the syntax highlighter’s CSS file do all of the styling, it worked again. I believe it was a “display: block” declaration that was causing the problem.

    Let me know if it works for you!
    Thanks,
    Brad

  3. emad permalink

    Thank you very much, this tutorial is very easy to learn.

  4. Elshan permalink

    Thanks for your tutorials!

  5. Michael permalink

    This material has really blessed my life, with the material I was able to find my way to CSS programming which seemed impossible to me before. Thanks.

Trackbacks & Pingbacks

  1. CSS Lesson 5: Understanding The Box Model Part 2: Margin | Learn Web Code

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS