CSS Box Model
- Content area
- Element’s content background is also applied to padding and border (you don’t usually see the background through the border; only if the border style has gaps is the background is visible through the gaps).
- Padding
- Padding cannot be a negative value.
- Padding takes the background of the content element.
- Border
- Border cannot be a negative value.
- Borders are generated using defined styles (if no “border-style” property is set, border is not visible).
- “border-color” property sets color (if no “border-color” is set, border takes foreground color of element’s content).
- Borders cannot have % widths, only % lengths.
- Margin
- Margins are always transparent.
- Margins can be a negative value.
- Margins can be set to “auto” (this is the way to horizontally center an element with CSS; remember to also specify the element's width when doing so.)
Note that when using shorthand properties, the order is top, right, bottom, left (clockwise, starting at the top).
Examples
CSS
p {
padding-top: 0;
padding-right: 0;
padding-bottom: 0;
padding-left: 0;
border-top-width: 0;
border-right-width: 0;
border-bottom-width: 0;
border-left-width: 0;
margin-top: 0;
margin-right: 0;
margin-bottom: 0;
margin-left: 0;
background-color: yellow;
}
Result
This is a paragraph with zero padding, zero border, zero margin, and a background-color of yellow.
Examples
CSS (using shorthand properties)
p {
padding: 0 0 0 0;
border-width: 0 0 0 0;
margin: 0 0 0 0;
background: yellow;
}
Result
This is a paragraph with zero padding, zero border, zero margin, and a background-color of yellow.
CSS (using shorthand properties)
p {
padding: 0;
border: 0;
margin: 0;
background: yellow;
}
Result
This is a paragraph with zero padding, zero border, zero margin, and a background-color of yellow.
CSS (using some shorthand properties)
p {
padding:0 5px 10px 15px;
border-style: solid dotted dashed double;
border-width: 1px 5px 10px 15px;
border-left-color: red;
margin: 0;
background-color: yellow;
}
Result
This is a paragraph with padding-top of zero, padding-right of 5 pixels, padding-bottom of 10 pixels, padding-left of 15 pixels, border-style-top of solid, border-style-right of dotted, border-style-bottom of dashed, border-style-left of double, border-top-width of 1 pixel, border-right-width of 5 pixels, border-bottom-width of 10 pixels, border-left-width of 15 pixels, border-left-color of red, zero margins, and a background-color of yellow.