CSS margin pushing the body element
Asked Answered
F

3

7

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: https://static.mcmap.net/file/mcmap/ZG-Ab5ovKRk0MC2AZV22bFljKmMva3/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.

Ferne answered 12/10, 2011 at 15:39 Comment(1)
Best solution is probably to add overflow:auto; on parent just as stated in the link provided by @Chris NicholsonLandlubber
T
3

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

Talkfest answered 12/10, 2011 at 15:43 Comment(0)
I
2

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

Inimitable answered 12/10, 2011 at 15:45 Comment(0)
O
0

I know this is an old question, but I just wanna point out that, in the example given in the question, one could use padding instead of margins:

<!-- HTML -->
<body>
  <div>
    content
  </div>
</body>

<!-- CSS -->
<style>
  html, body {
    box-sizing: border-box; /* padding makes part of the */
    height: 100%;           /*  box whose height is 100% */
    margin: 0;
    padding: 0;
    outline: 1px solid blue;
  }
  
  body {
    padding: 20px;
  }
  
  div {
    outline: 1px solid red;
  }

</style>
Overtire answered 12/6, 2019 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.