Padding
- The padding property is used to specify the space between the content of an element and its border.
- Padding property can be applied to various HTML elements like divs, paragraphs, and headings.
Syntax:
body {
padding: value;
}
Ways to set padding property:
Setting Padding for All Sides Equally:
selector {
padding: 10px; /* 10 pixels of padding on all sides */
}
Setting Padding for Individual Sides:
selector {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
Shorthand Syntax for All Sides:
shorthand notation is used to set padding for all sides at once in the order of top, right, bottom, and left:
selector {
padding: 20px 20px 10px 30px; /* top, right, bottom, left */
}
Padding Properties:
Padding Values:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: greenyellow;
}
p.padding {
padding-top: 50px;
padding-right: 100px;
padding-bottom: 150px;
padding-left: 200px;
}
</style>
</head>
<body>
<p> paragraph with no specified padding.</p>
<p class="padding"> paragraph with specified paddings.</p>
</body>
</html>
Output:
Difference Between Padding and Margin
FEATURES | MARGIN | PADDING |
---|---|---|
Definition | Space outside the element's border. | Space inside the element's border, between the border and the content. |
Affects Layout | Yes, adds space outside the element, affecting the layout around it. | Yes, adds space inside the element, affecting the internal layout. |
Position | Positioned outside the element's border. | Positioned inside the element's border. |
Negative Values | Allowed, can create overlapping elements. | Not allowed, values must be non-negative. |
Impact on Box Model | Affects the outer space of the element, impacting its position relative to other elements. | Increases the size of the element's box, affecting its content area. |
Collapsing Behavior | Adjacent vertical margins may collapse. | Padding does not collapse. |
Impact on Background Color | Does not affect the background color of the element. | Affects the background color of the element (background color extends to the padding area). |
Usage | Used to create space between elements. | Used to create space within an element, providing spacing around the content. |
Properties | margin-top , margin-right , margin-bottom , margin-left | padding-top , padding-right , padding-bottom , padding-left |