The padding property is used to create space around an element's content, inside of any defined borders. Think of it as 'breathing room' for the text or content inside a box.
Like margins, CSS has individual properties for each side of the box:
padding-toppadding-rightpadding-bottompadding-leftp {
padding-top: 10px;
padding-bottom: 25px;
padding-left: 20px;
padding-right: 15px;
}
You can write all padding properties in a single line. The shorthand follows the clockwise direction: Top, Right, Bottom, Left.
/* Four values: Top, Right, Bottom, Left */
padding: 25px 50px 75px 100px;
/* Three values: Top, Right/Left, Bottom */
padding: 25px 50px 75px;
/* Two values: Top/Bottom, Right/Left */
padding: 15px 30px;
/* One value: All four sides */
padding: 20px;
When you add padding to an element, it is typically added to the total width of that element. If an element has a specified width, adding padding will make it wider than its set width.
box-sizing: border-box; to keep the width of an element constant regardless of the padding added.
/* Content is wider than 300px */
.box1 {
width: 300px;
padding: 25px;
border: 1px solid black;
}
/* Content remains 300px width */
.box2 {
width: 300px;
padding: 25px;
border: 1px solid black;
box-sizing: border-box; /* Highly Recommended! */
}
Unlike the margin property, the padding property cannot have negative values. Padding must always be 0 or a positive number.
Padding is essential for making clickable buttons readable and attractive.
.my-button {
padding: 12px 24px; /* Makes the button look professional */
background-color: #2e7d52;
color: white;
border: none;
}