🤯 50% Off! 700+ courses, assessments, and books

How to Set CSS Margins and Padding (And Cool Layout Tricks)

Baljeet Rathi
Share

When I was just starting to learn CSS, the margin and padding properties always confused me. They seemed very similar and in some cases appeared to produce the same result. In this tutorial, you’ll learn the difference between CSS margins and padding and how these properties affect the space between elements on a webpage. We’ll also discuss margin collapsing, the effect of using different units while creating responsive websites, and conclude with some layout tricks you can do with CSS margins and padding.

How to Set CSS Margins and Paddings

The Box Model

Elements in CSS are represented as a rectangular box. The size of this rectangular box is determined by the element’s:

  • Content
  • Padding
  • Border
  • Margin

The content area of an element lies in the middle of the element. The padding surrounds the element’s content . The borders in turn surround the padding. The margin of the element is its external layer, i.e., it lies outside the element.

The following diagram should make the arrangement clearer.

Visual representation of CSS margins, padding, border and content

As apparent from the diagram, the padding of an element is the layer that extends from the outer edge of the element’s content to the inner edge of its border. This property is used to control the spacing between the element’s border and its main content. The padding applied on an element affects its size on the webpage. It does not affect the distance between different elements on a webpage.

When you want to increase or decrease the amount of space in-between elements, you should use the margin property. The margin applied on an element won’t have any effect on its size.

One important thing related to boxes that you should keep in mind is that the sizes of all the boxes on a webpage depends on the box model being used. There are two different box models:

  • W3C box model
  • Traditional box model

See the Pen Choosing a Box Model by SitePoint (@SitePoint) on CodePen.

The W3C box model considers the width of the element to be equal to the content of the box excluding its padding and border. Padding and border are added on top of whatever dimensions you set for the element, which could have some unpredictable consequences on your page layout.

For example, let’s consider a box with a width of 200px and a height of 200px, padding of 10px on all sides and a border of 2px all round. The browser does not see it simply as a 200px box. Rather, the browser calculates the horizontal space necessary to display the box as being 224px: 200 (width) + 2 (left border) + 10 (left padding) + 10 (right padding) + 2 (right border) = 224px. Given that the element is a perfect square, the height will also compute to 224px.

On the other hand, the traditional box model considers the width of the element to be equal to the sum of the content, padding and the border applied to the box. On the layout front, this means that, if your box is 200px wide, the browser computes the horizontal space it needs to display the box as being 200px wide, including padding and border. This yields more predictable results and it’s easier to work with.

W3C box model and traditional box model

All browsers use the W3C box model by default. You can choose to specify the box model explicitly by setting the value of the box-sizing property to either content-box (W3C box model) or border-box (traditional box model). The traditional box model, being more intuitive, is the most popular approach among web developers.

Here is how you can set the box-sizing property to follow the traditional box model on your web project:

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

If you learn best by doing, try experimenting with this fun interactive demo by Guy Routledge.

Setting Margins and Paddings

You can control the padding applied to the four sides of an element using the padding-top, padding-right, padding-bottom and padding-left properties. You can also specify the padding using the shorthand padding property.

  • When a single padding value is present, CSS uses this value to determine the padding of all four sides:

    /* all four sides */
     padding: 10px;
  • When two values are present, the first value determines the top and bottom padding and the second value determines the left and right padding:

    /* vertical | horizontal */
     padding: 2em 4em;
  • When three values are present, the first value determines the top padding, the second value determines the left and right padding and the third value determines the bottom padding:

    /* top | horizontal | bottom */
    padding: 1em 20px 2em;
  • When all four values are present, they set the top, right, bottom and left padding in this exact order:

    /* top | right | bottom | left */
    padding: 10px 10% 2em 15%;

In the following demo, the orange background represents the content area of different elements and the white area between the borders and the content area represents the padding that we applied on each element:

See the Pen Setting Paddings by SitePoint (@SitePoint) on CodePen.

Just like with padding, you can control the margin applied to the four sides of an element using the margin-top, margin-right, margin-bottom and margin-left properties. You can also specify the margin for all the four sides of an element using the shorthand margin property.

/* all four sides */
margin: 10px;

/* vertical | horizontal */
margin: 2em 4em;

/* top | horizontal | bottom */
margin: 2em auto 2em;

/* top | right | bottom | left */
margin: 10px 10% 2em 15%;

Things to Keep in Mind

Using the Right Units

When applying margins and padding, you should avoid using absolute units . This is because these units won’t adapt to the changes in font size or screen width.

Let’s say you have set the width of an element to 50% and also applied a margin of 15px on it. At 1200px, its width would be 600px and its margin would be 15px. At 769px, its width would be 384px and its margin would still be 15px.

In this case, the width of the element has changed by 36% but its margin still has the same old value. In most cases, this might not be a big deal. However, setting the element’s margin in terms of percentages will allow you to have finer control over the layout of the webpage on all screen sizes. This way you can make everything proportional without any sudden jumps in the value of applied margins and padding.

See the Pen Setting Margins as Percentage by SitePoint (@SitePoint) on CodePen.

Similarly, you may want to add padding to text elements on a webpage. Generally, you would like the padding to be proportional to the font size of the corresponding element. This cannot be achieved with absolute units. However, if the padding is specified in terms of em units, it will automatically scale with the font size. Here is a demo that shows this scaling in action.

See the Pen Right Units for Margins and Padding by SitePoint (@SitePoint) on CodePen.

How Browsers Compute Margin and Padding Values for Different Units

Browsers compute the final margin and padding values for an element differently based on the unit being used.

Any margin or padding that has been specified as a percentage is calculated based on the width of the containing element. This means that padding of 5% will be equal to 5px when the parent element is 100px wide and it will be equal to 50px when the parent element is 1000px wide. Remember that the top and bottom values are also calculated based on the width of the parent element.

In case of em units, the computed value for margin and padding is based on the font size of the element. In the previous CodePen demo, the padding applied to the bottom three text elements is 1em. However, the computed value of padding is different in each case because of the different font size.

There are also four different viewport based units called vw, vh, vmin and vmax. The computed value of margin and padding in this case is based on the viewport. For example, a padding of 5vw will be equal to 25px when the viewport is 500px wide and a padding of 10vw will be equal to 50px for the same viewport width. You can read more about these units in CSS Viewport Units: A Quick Start on SitePoint.

As a beginner, knowing how these different units work can help you quickly figure out why the padding or margin of HTML elements is changing based on the parent element’s size, font size or even the viewport, which gives you the power to take control of your layout.

Dealing with Collapsing Margins

Another concept that you should be aware of is collapsing margins. In certain situations, the top and bottom margins on two elements can collapse into one. This phenomenon is called margin collapsing.

Let’s say you have two elements side by side, i.e., adjacent siblings. If the margin-bottom property on the first element is set to 40px and the margin-top property on the second element is set to 25px, the final margin between the two elements will not be 65px. Its actual value will be equal to the value of the bigger margin i.e., 40px.

Similarly, margins can also collapse between a parent element and its first/last child. This happens when there is no border, padding or inline content to separate the child’s and parent’s respective margins. In this case, if there is no padding or border on the parent element, the child’s margin would look as if it were bleeding out of the parent.

One way to avoid this situation is to add a barrier between the parent’s margin and the child’s. This can be done by either using a border or a padding. The following demo shows how adding a border or padding on the parent element can avoid the bleeding margin.

In case of negative margins, the final value of the collapsed margins is the sum of the largest positive margin and the smallest negative margin.

You can read more on this topic in Collapsing Margins, by Adam Roberts.

Interesting Uses of Margins and Padding

Sometimes, you can use CSS margin and padding properties to solve a number of layout related issues. Here are a few examples:

Center Elements within Their Parents

Centering block-level elements horizontally inside their parent is very easy with the help of the margin property. All you have to do is set the value of the margin-left and margin-right properties of the element to auto.

.child {
  margin: 10px auto;
}

In the following demo, you can see three instances of a parent element: the first one is set to be a block-level element, the second one to be an inline-block element, and the third one is a block-level element that has been floated to the right. The child element results to be centered horizontally in all cases.

Maintaining Image Aspect Ratios

Often, the images on a webpage do not have a fixed aspect ratio. If you have to show all images with the same aspect ratio, CSS padding can help.

The trick is to set the height of the parent element to zero and its padding-top property to be equal to the value of the desired aspect ratio expressed as a percentage.

For example, an aspect ratio of 16:9 can be achieved by using padding: 56.25% 0 0 0. Here, the value 56.25 was obtained after calculating (9/16)*100. The same method can be used to calculate the percentage of padding for any other aspect ratio.

See the Pen Maintaining Image Aspect Ratio by SitePoint (@SitePoint) on CodePen.

You can read more about this technique on How to Maintain Image Aspect Ratios in Responsive Web Design, by Craig Buckler.

Other interesting, although a bit more advanced uses of margins and padding, include creating full-width containers inside limited width parents and adding consistent spacing at the bottom of different modules in a webpage. You can consider these to be your next steps in mastering CSS margins and padding.

Conclusion

If you are new to CSS, I hope this tutorial has helped you understand the differences between margins and padding. You should also be comfortable setting margins and padding with the shorthand syntax and appropriate units. In the last section, I mentioned a few interesting layout-related uses of these properties and pointed you to further resources to find out more.

If you know any other tips about CSS margins and padding, please share them with us in the comments.

Take your CSS skills to the next level with our book CSS Master, 2nd Edition by Tiffany B. Brown – covering CSS animations, transitions, transformations and much more.