Special Behavior of Margins
In this lesson, we will explore some special kinds of behavior of the margin property. Let's begin!
We'll cover the following...
CSS has a feature called collapsing margins where two separate margins become a single margin.
The Listing below shows two situations when this phenomenon occurs.
Listing: Spacing with percentages
<!DOCTYPE html> <html> <head> <title>Spacing with percentages</title> <style> body { font-family: Verdana, Arial, sans-serif; } h1 { margin-bottom: 25px; } p { margin-top: 20px; } #warning { border: 2px dotted dimgray; padding: 8px; } h2 { margin: 16px; } #head { background-color: navy; color: white; } #head p { margin: 16px; } </style> </head> <body> <h1>Heading with margin-bottom: 25</h1> <p>Paragraph with margin-top: 20</p> <div id="warning"> <h2>Did you know...</h2> <div id="head"> <p>It is special!</p> </div> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit fusce vel sapien elit in malesuada semper mi, id sollicitudin. </p> </div> </body> </html>
According to the style sheet, the <h1>
tag has a 25-pixel bottom margin, and the adjacent <p>
tag has a 20-pixel top margin. These two are 45-pixels altogether. However, as ...