Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS margin pushing the body element

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: http://i54.tinypic.com/29ve1zl.jpg

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.

like image 515
Rich Avatar asked Oct 12 '11 15:10

Rich


People also ask

How do I stop margin collapsing CSS?

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.

What does margin 10px 5px 15px 20px mean?

margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.

How do I fix the margin in CSS?

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 .

Is it bad practice to use negative margins CSS?

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.


2 Answers

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

like image 123
Chris Avatar answered Oct 02 '22 11:10

Chris


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

like image 38
Jrod Avatar answered Oct 02 '22 11:10

Jrod