DEV Community

Cover image for CSS Padding
HyperCode
HyperCode

Posted on • Updated on • Originally published at devwares.com

CSS Padding

The CSS padding properties are used to generate space around an element's content, inside any defined borders. Padding does not include margins or borders.

Padding - Individual Sides

CSS allows you to set the padding for individual sides of an element:

div {  
padding-top: 50px;  
padding-right: 30px;  
padding-bottom: 50px;  
padding-left: 80px;
   }
Enter fullscreen mode Exit fullscreen mode

In this example, the top padding is 50px, the right padding is 30px, the bottom padding is 50px, and the left padding is 80px.

Shorthand Property: Padding

The padding property is a shorthand property for padding-top, padding-right, padding-bottom, and padding-left.

div {  
padding: 25px 50px 75px 100px;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the top padding is 25px, the right padding is 50px, the bottom padding is 75px, and the left padding is 100px.

You can also provide less than four values:
If you provide one value, it applies to all sides. For example, padding: 25px;.

If you provide two values, the first value applies to the top and bottom padding, and the second value applies to the right and left padding. For example, padding: 25px 50px;.

If you provide three values, the first value applies to the top padding, the second value applies to the right and left padding, and the third value applies to the bottom padding. For example, padding: 25px 50px 75px;.

Padding and Element Width

By default, the width of an element is calculated like this: width + border = actual width of an element.

If you set the CSS box-sizing property to border-box, the padding and border are included in the element's total width and height:

div {  box-sizing: border-box;}
Enter fullscreen mode Exit fullscreen mode

In this example, if you set a div element to be 300px wide, that 300px will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements.

Top comments (0)