CSS Padding

This padding property is used to define the space between the element content and the element border.

It is different from CSS margin in the way that CSS margin defines the space around elements. CSS padding is affected by the background colors. It clears an area around the content.

We can control top, bottom, left and right padding property independently. We can also change all properties at once by using shorthand padding property.

Property         Description
paddingIt is used to set all the padding properties in one declaration.
padding-leftIt is used to set left padding of an element.
padding-rightIt is used to set right padding of an element.
padding-topIt is used to set top padding of an element.
padding-bottomIt is used to set bottom padding of an element.
Input:-

Index.html
	
<body>
	  <div>
		This is a div element
	 </div>
</body>

Style.css
	
div {
    padding-top: 50px;  
    padding-right: 100px;  
    padding-bottom: 150px;  
    padding-left: 200px;  
}

Output:-

Value  Value  
lengthIt is used to define fixed padding in pt, px, em etc.
%It defines padding in % of containing element.

The Padding Shorthand Property

The padding property is a shorthand property to avoid setting padding of each side separately, i.e., padding-top, padding-right, padding-bottom and padding-left.

h1 {
    padding: 50px; /* apply to all four sides */
}
p {
    padding: 25px 75px; /* vertical | horizontal */
}
div {
    padding: 25px 50px 75px; /* top | horizontal | bottom */
}
pre {
    padding: 25px 50px 75px 100px; /* top | right | bottom | left */
}

This shorthand notation can take one, two, three, or four whitespace separated values.

  • If one value is specified, it is applied to all four sides.
  • If two values are specified, the first value is applied to the top and bottom side, and the second value is applied to the right and left side of the element’s box.
  • If three values are specified, the first value is applied to the top, second value is applied to right and left side, and the last value is applied to the bottom.
  • If four values are specified, they are applied to the top, right, bottom and the left side of the element’s box respectively in the specified order.
Input:-

Index.html
	
<body>
	  <div>
		This is a div element
	 </div>
</body>

Style.css
	
div {
    padding: 50px 100px 150px 200px;  
}

Output:-