I saw the following css in the Sonata project.
HTML:
<div class="content">
<div class="header"></div>
</div>
CSS:
.content {
padding: 20px;
margin: 0 -20px; /* negative indent the amount of the padding to maintain the grid system */
}
.header {
padding: 20px 20px 10px;
margin: -20px -20px 20px;
}
My question is, what is the purpose/advantage of having positive paddings and then negate them with negative margins? The code does have a comment on negative margin but I don't really get it. Why not just set both margin and padding to 0?
Thanks!
It is possible to give margins a negative value. This allows you to draw the element closer to its top or left neighbour, or draw its right and bottom neighbour closer to it.
The downside of negative margins is they are difficult to debug and will make your CSS harder to read. The most often misuses of negative margins that I encounter is when it is used to make up for incorrect layouts elsewhere on the site. This is indeed bad practice.
Margins can be negative or positive: You can set margin values to be negative if you want elements to overlap. Padding values, however, can only be positive. Margins can be automatically centered: Margins have an "auto" value you can choose if you want to center an element horizontally in a space.
Gross profit margin can turn negative when the costs of production exceed total sales. A negative margin can be an indication of a company's inability to control costs.
One common use of padding offset by a negative margin like this is to fix browsers navigating to the wrong place when using fragment identifiers in combination with a position: fixed
header.
Suppose I have a page like this...
<div class="fixed-navbar">Navbar Stuff!</div>
<a href="#interesting-content">Link to interesting content below</a>
<p>Lots of content that takes up space and makes the page scroll...</p>
<h2 id="interesting-content">Some interesting content</h2>
<p>Bla bla bla</p>
<p>More really tall content</p>
... where the .fixed-navbar
has this CSS:
position: fixed;
height: 50px;
When I visit my page and click the link, the browser will scroll the <h2>
up to the top of the page... resulting in it underlapping the fixed navbar! This is probably undesirable. (Fiddle)
However, we can fix this with the following CSS:
#interesting-content {
padding-top: 50px;
margin-top: -50px;
}
(Fiddle)
Now, when we ask the browser to navigate to the fragment identifier, it navigates to the top of the padding, one navbar-height above the actual content. This positions the actual content right where we want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With