Padding in CSS


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

    1. padding: This is a shorthand property for setting all four padding properties (padding-top, padding-right, padding-bottom, and padding-left) in one declaration.

    2. padding-top: Specifies the padding area on the top of an element.

    3. padding-right: Specifies the padding area on the right of an element.

    4. padding-bottom: Specifies the padding area on the bottom of an element.

    5. 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 20px
    • padding-right to 30px
    • padding-bottom to 40px
    • padding-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 and padding-bottom to 20px
    • padding-right and padding-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>


In this example, the .box element will have a light blue background with 20 pixels of padding on all sides, making the text inside the box appear away from the border.