Padding and Element Width
The CSS width property sets the width of an element's content area. The content area is the part inside the padding, border, and margin (the box model).
So if an element has a set width, any padding is added on top of that width. This is often not what you want.
For example, a <div> with a width of 300px and 25px of padding actually takes up 350px (300 + 25 + 25).
Example
The set width is 300px, but the padding pushes the total width to 350px.
<style> block, give a <div> width 300px and padding 25px, plus a border and background. The actual width becomes 350px (300 + 25 + 25). Put text inside.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div {
width: 300px;
padding: 25px;
border: 1px solid #4CAF50;
background-color: lightblue;
}
</style>
</head>
<body>
<div>The set width is 300px, but the padding makes the total width 350px.</div>
</body>
</html>
Padding and box-sizing
The box-sizing property sets how the width and height of an element are worked out: whether they include the padding and border or not.
It can take these values:
content-box— the default. The width and height cover only the content, not the padding or border.border-box— the width and height cover the content, padding, and border.
So to keep the width at 300px no matter the padding, use box-sizing: border-box. The element keeps its total width, and more padding just leaves less room for the content.
Example
With box-sizing: border-box, the total width stays 300px even with padding.
<style> block, give a <div> width 300px, padding 25px, and box-sizing: border-box, plus a border and background. The total width stays 300px. Put text inside.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
border: 1px solid #4CAF50;
background-color: lightblue;
}
</style>
</head>
<body>
<div>With box-sizing: border-box, the total width stays 300px even with padding.</div>
</body>
</html>
All CSS Padding Properties
A summary of the padding properties:
padding— sets all the padding in one declaration.padding-bottom— sets the bottom padding.padding-left— sets the left padding.padding-right— sets the right padding.padding-top— sets the top padding.