I'm setting a margin for a div element, however the body element also gets that margin.
Consider this code:
<!-- HTML -->
<body>
<div>
</div>
</body>
<!-- CSS -->
<style>
html,body {
height:100%;
margin:0;
padding:0;
outline:1px solid blue;
}
div {
margin:20px;
outline:1px solid red;
}
</style>
This is the result and the problem:
So far I've solved the problem by adding a border:1px solid transparent;
property to the body element. This ruins the 100% height because scrollbars appear due to the 1px
border. Why does this happen?
POSSIBLE SOLUTION (thanks for the help): Add a padding-top:1px
and a margin-top:-1px
, this way the 100% height doesn't gets ruined with the scrollbars and your are avoiding margin collapsing.
How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.
margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.
Adjusting the Margin Size of an HTML Element With CSS You can remove this margin by setting the top and left margin to zero. Like the padding and border, the sizes of specific sides of the margin can be set using margin-left , margin-right , margin-top , and margin-bottom .
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.
This sounds similar to a problem I had: Margins and negative margins. I solved mine by putting a padding-top rather than a border, maybe this works with your design slightly better? Otherwise try this link: http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html
This is caused by an effect known as collapsing margins.
Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.
http://www.w3.org/TR/css3-box/#collapsing-margins
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