Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is how margins work.. the margin is the space between the next element with a margin / padding / similar. It is not necessarily defined as its parent element. <a href="http://www.w3.org/TR/CSS2/box.html" rel="nofollow noreferrer">Consult the spec</a>.</p> <p>Here are some things you can do as a workaround</p> <h2>Use Padding Instead</h2> <p>This just means instead of using <code>margin-top: 10px;</code> you use <code>padding-top: 10px;</code>. This is not suitable for every occasion.</p> <h2>Weird Hack I Discovered</h2> <p>I doubt I discovered this initially, but the other day I solved the problem like this. I had a <code>&lt;div id="header" /&gt;</code> that I wanted to give a top margin too, and its top margin was pushing the parent (<code>body</code> element) down as well. So I did this on the <code>body</code> element...</p> <pre><code>body { padding-top: 1px; margin-top: -1px; } </code></pre> <p>This made my margin work. You can also try using a border, like <code>border: 1px solid #ccc</code>.</p> <p>It would also be wise to leave a note in the CSS comments to explain why you have that peculiar pair of rules. I just added <code>/* this is to stop collapsing margins */</code>.</p> <h2>Further Reading</h2> <p>Check out these <a href="https://stackoverflow.com/questions/2176520/why-would-margin-not-be-contained-by-parent-element">other</a> <a href="https://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element">questions</a> on Stack Overflow</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload