Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Found an alternative at <a href="https://stackoverflow.com/questions/1878997/child-elements-with-margins-within-divs">Child elements with margins within DIVs</a> You can also add:</p> <pre><code>.parent { overflow: auto; } </code></pre> <p>or:</p> <pre><code>.parent { overflow: hidden; } </code></pre> <p>This prevents the margins to <a href="http://www.w3.org/TR/CSS2/box.html#collapsing-margins" rel="noreferrer">collapse</a>. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:</p> <pre><code>.parent { padding-top: 1px; margin-top: -1px; } </code></pre> <hr> <p><strong>Update by popular request:</strong> The whole point of collapsing margins is handling textual content. For example:</p> <pre><code>&lt;style type="text/css"&gt; h1, h2, p, ul { margin-top: 1em; margin-bottom: 1em; } &lt;/style&gt; &lt;h1&gt;Title!&lt;/h1&gt; &lt;div class="text"&gt; &lt;h2&gt;Title!&lt;/h2&gt; &lt;p&gt;Paragraph&lt;/p&gt; &lt;/div&gt; &lt;div class="text"&gt; &lt;h2&gt;Title!&lt;/h2&gt; &lt;p&gt;Paragraph&lt;/p&gt; &lt;ul&gt; &lt;li&gt;list item&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Because the browser collapses margins, the text would appear as you'd expect, and the <code>&lt;div&gt;</code> wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <code>&lt;h2&gt;</code> and <code>&lt;p&gt;</code> won't add up, but slide into each other (they collapse). The same happens for the <code>&lt;p&gt;</code> and <code>&lt;ul&gt;</code> element.</p> <p>Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new <a href="http://www.w3.org/TR/CSS2/visuren.html#block-formatting" rel="noreferrer">block formatting context</a> in CSS speak. The <code>overflow</code> or margin trick will give you that.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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