Search
Close this search box.
Search
Close this search box.

Margins, padding and borders

Understanding the Box Model

Surrounding the content are different properties that make up the box:

  •  padding is the space between the content and the content’s border. Padding is what separates a photo from the border that frames the photo.
  • border is the line that’s drawn around each edge of the box. You can have a border around all four sides, on just a single side, or any combination of sides.
  • background-color fills the space inside the border, including the padding area.
  • margin is what separates one tag from another. The space that commonly appears between the tops and bottoms of paragraphs of text on a web page, for example, is the margin.

Margin and Padding Shorthand

You’ll frequently want to set all four sides of a style’s margin or padding. But typing out all four properties (margin-right, margin-left, and so on) for each style gets tedious. Fear not: You can use the shortcut properties named margin and padding to set all four properties quickly:

margin: 0 10px 10px 20px;
padding: 10px 5px 5px 10px;

Note: If the value used in a CSS property is 0, then you don’t need to add a unit of measurement. For example, just type margin: 0; instead of margin: 0px;.

The order in which you specify the four values is important. It must be top, right, bottom, and left. If you get it wrong, you’ll be in trouble. In fact, the easiest way to keep the order straight is to remember to stay out of TRouBLe—top, right, bottom, and left.

If you want to use the same value for all four sides, it’s even easier—just use a single value. If you want to remove margins from all <h1> tags, you can write this style:

h1 {
    margin: 0;
}

Similarly, use shorthand to add the same amount of space between some content
and its border:

padding: 10px;

Note: When you’re using the same value for both top and bottom and another value for both left and right, you can use two values. margin: 0 2em; sets the top and bottom margins to 0 and the left and right margins to 2ems.

More coming soon…