Padding in CSS is the space between the content of an element and its border.
It is used to create a gap around the content inside an element, providing visual spacing and improving layout readability.
Properties of Padding
padding
: This is a shorthand property for setting all four padding properties (padding-top
,padding-right
,padding-bottom
, andpadding-left
) in one declaration.padding-top
: Specifies the padding area on the top of an element.padding-right
: Specifies the padding area on the right of an element.padding-bottom
: Specifies the padding area on the bottom of an element.padding-left
: Specifies the padding area on the left of an element.
Syntax
Individual sides:
padding-top: length | percentage; padding-right: length | percentage; padding-bottom: length | percentage; padding-left: length | percentage;
Shorthand:
padding: top right bottom left; padding: top right-left bottom; padding: top-bottom right-left; padding: all-sides;
Examples
Using Individual Properties:
<style> .box { padding-top: 20px; padding-right: 30px; padding-bottom: 40px; padding-left: 50px; } </style> <div class="box">This is div with padding</div>
Using Shorthand Property:
<style> .box { padding: 20px 30px 40px 50px; /* top right bottom left */ } </style> <div class="box">This is div with padding</div>
This sets:
padding-top
to 20pxpadding-right
to 30pxpadding-bottom
to 40pxpadding-left
to 50px
Using Shorthand with Fewer Values:
<style> .box { padding: 20px 30px; /* top-bottom right-left */ } </style> <div class="box">This is div with padding</div>
This sets:
padding-top
andpadding-bottom
to 20pxpadding-right
andpadding-left
to 30px
Using Percentage Values:
<style> .box { padding: 10%; } </style> <div class="box">This is div with padding</div>
This sets padding on all four sides to 10% of the width of the containing element.
Practical Example
Here's an HTML and CSS example demonstrating the padding property:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Padding Example</title> <style> .box { width: 200px; height: 100px; border: 2px solid black; padding: 20px; background-color: lightblue; } </style> </head> <body> <div class="box"> This box has padding. </div> </body> </html>