2.1 Internal Padding
Internal padding (padding) defines the space between the content of an element and its borders. You can set padding for each side of the element: top, right, bottom, and left. Padding can be useful for creating space around an element's content so it doesn't cling to the borders.
Usage Example
In this example, an element with the class .padding is given 20 pixels of padding on all sides, creating space around the content.
.padding {
background-color: #e0e0e0;
padding: 20px;
border: 2px solid #000;
}
<div class="padding">
This is an element with internal padding.
</div>
2.2 External Margins
External margins (margin) define the space between the element and neighboring elements. Margins can be set for each side of the element: top, right, bottom, and left. They're useful for creating space between elements to prevent them from overlapping.
Usage Example:
.margin {
background-color: #e0e0e0;
border: 2px solid #000;
margin: 20px;
}
<div class="margin">
This is an element with external margins.
</div>
2.3 Block Model Component Interaction
All four components of the block model (content, padding, borders, and margins) work together to determine the overall size and positioning of an element on a page.
Example of Component Interaction:
.box {
background-color: #e0e0e0;
padding: 20px;
border: 5px solid #000;
margin: 30px;
width: 200px;
}
<div class="box">
This is an element with external and internal padding.
</div>
Code Explanation:
- Content: the text inside the element
- Padding: 20 pixels creating space between the content and the border
- Borders: 5 pixels surrounding the element
- Margins: 30 pixels creating space between the element and other elements on the page
2.4 Negative Margins
Margins can have negative values, which causes elements to overlap.
.negative-margin {
background-color: #e0e0e0;
padding: 20px;
border: 2px solid #000;
margin-top: -12px;
}
<div>
This is a regular element
</div>
<div class="negative-margin">
This is an element with negative top margin.
</div>
2.5 Margin Collapse
When vertical margins of two adjacent blocks meet, they can collapse into a single margin, which equals the bigger of the two.
.box1 {
background-color: #e0e0e0;
padding: 20px;
border: 2px solid #000;
margin-bottom: 30px;
}
.box2 {
background-color: #d0d0d0;
padding: 20px;
border: 2px solid #000;
margin-top: 20px;
}
<div class="box1">
This is the first element.
</div>
<div class="box2">
This is the second element. Margins collapse to 30 pixels.
</div>
GO TO FULL VERSION