<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ CSS Margins - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ CSS Margins - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 17:00:39 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/css-margins/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is Margin Collapse in CSS? And How to Avoid It ]]>
                </title>
                <description>
                    <![CDATA[ What is Margin Collapse? Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin.  You can visualize this as an arm... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-margin-collapse-and-how-to-avoid-it/</link>
                <guid isPermaLink="false">66bc4cc173c9920bb20c0e03</guid>
                
                    <category>
                        <![CDATA[ CSS Margins ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Natalie Pina ]]>
                </dc:creator>
                <pubDate>Tue, 11 Jan 2022 18:07:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/domino-g6f10860f9_1280.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-is-margin-collapse">What is Margin Collapse?</h2>
<p>Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin. </p>
<p>You can visualize this as an arm wrestling match, where the larger margin will take over and win.</p>
<p>It is important to clarify what it means to be the larger number. </p>
<p>If a margin of 70px collides with a margin of 90px, the 90px margin will win. If a margin of -70px collides with a margin of -90px, -90px will win. </p>
<p>Although a negative number is technically a smaller value on a mathematical scale than a positive number, with margin collapse instead it is helpful to remember that a higher numerical value will hold the higher significance. </p>
<p>Collapsing is relevant regardless of the unit of measurement such as pixels, rem, em, or percentages. These units can be calculated against each other even with mixed use.</p>
<p>In various scenarios this interaction can become problematic. For example, if you are creating a reusable component that is expected to have a set consistent margin space surrounding it, regardless of placement. </p>
<p>Inconsistencies may occur depending on, where that component is placed as the margin may interact with another. Fortunately, there are precautions we can take to avoid this.</p>
<p>Margin collapse can cause unexpected behaviors in your layout. You'll likely see applied spacing that doesn't seem to match up with what you expect. </p>
<p>Instead of trying to increase margins by adding extra pixels until the spacing is correct, you can learn the inner workings of the margin property so you can recognize when collapsing can occur. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/margin-collapse-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-margin-collapse-code-example">Margin Collapse Code Example</h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"one"</span>&gt;</span>Block-Level Element One<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"two"</span>&gt;</span>Block-level Element Two<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span><span class="hljs-selector-class">.one</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">30px</span>;
}

<span class="hljs-selector-tag">div</span><span class="hljs-selector-class">.two</span> {
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">100px</span>;
}
</code></pre>
<h2 id="heading-negative-margins">Negative Margins</h2>
<p>Negative margin values are also susceptible to margin collapse. They work as positive margins do, where the greater number will take over.   </p>
<p>The result of a -30px margin and a -100px collision will result in a margin space of -100px.</p>
<h3 id="heading-mixing-negative-and-positive-margins">Mixing Negative and Positive margins</h3>
<p>When a negative and a positive margin interact, the pixels will be added together, cancelling each other out. Here is where some math will factor in. </p>
<p>For example, a margin of -30px and a margin of 10px will result in a shared margin space of -20px. Alternatively, a margin of 10px and a margin of -1opx will result in no margin spacing (-10 + 10 = 0)! </p>
<h2 id="heading-how-to-recognize-margin-collapse">How to Recognize Margin Collapse</h2>
<p>There are different scenarios when margins can collapse. Review the comparisons below to gain a better grasp on when margin collapse can happen.</p>
<h3 id="heading-margin-collapse">Margin Collapse</h3>
<ul>
<li>Elements are block-level, such as <code>div</code> or <code>p</code></li>
<li>Vertical margins will collapse</li>
<li>Collapse will only occur in Flow Layout, which is the default layout mode</li>
<li>An "invisible" element like a  <code>&lt;br/&gt;</code> will not stop margin collapse</li>
</ul>
<h3 id="heading-no-margin-collapse">No Margin Collapse</h3>
<ul>
<li>Horizontal sibling elements will not collapse</li>
<li>No margin collapse in Flex, Grid, or Positioned Layout </li>
<li>Margin collapse can stack and create a domino effect of siblings effecting each other</li>
<li>A <code>&lt;hr/&gt;</code> element between vertical siblings can prevent collapsing</li>
</ul>
<h3 id="heading-how-to-inspect-your-margins">How to Inspect your Margins</h3>
<p>The Inspect feature in your browser is a great tool to get a visual on your margins, padding, and other aspects of the Box Model. This will help you to see if margins are shared.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/boxmodel.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Box Model</em></p>
<h2 id="heading-how-to-avoid-margin-collapse">How to Avoid Margin Collapse</h2>
<p>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.</p>
<p>Also, consider the layout mode when adding a margin. Take note of which layout mode you are in and watch out for margin collapse whenever in normal Flow Layout. </p>
<p>To add spacing between siblings and avoid margin collapse altogether, consider using Flexbox or Grid and utilizing their gap functionalities.</p>
<p>You can also consider using a component library aligned with the spacing guidelines of a particular design system. Or you can use an open-source library that has already resolved margin collapse issues. You can also setup a system of design for you team where you can use consistent margin and padding throughout your UI. </p>
<p>Finally, try to develop a sense for when margin collapse is occurring. Now that you are more aware of this behavior, you will start to notice it more frequently. </p>
<p>Use your trusty browser inspector tools when your margin collapse radar is activated. If you find it, remove it to prevent repeated use of the style as it may be reused and cause issues in the future.</p>
<h3 id="heading-resources-on-margin-collapse">Resources on Margin Collapse</h3>
<p>If you'd like to do a deeper dive on margin collapse, I highly suggest reading <a target="_blank" href="https://www.joshwcomeau.com/css/rules-of-margin-collapse/">The Rules of Margin Collapse</a> by Josh W. Comeau. </p>
<p>I also recommend his comprehensive course <a target="_blank" href="https://css-for-js.dev/">CSS for JavaScript Developers</a> if you'd like to fill in any gaps in your CSS knowledge and learn more about topics such as this.</p>
<h2 id="heading-summary">Summary</h2>
<p>Margin collapse may be a CSS behavior that you have previously experienced and didn't yet had a definition for, or you might not have had all the tools available to avoid it. </p>
<p>This tricky aspect of the margin property can often go overlooked and wreak havoc through expected behaviors. Understanding these effects can help to improve your UI and reduce the number of bugs in your CSS.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Understand and Work With CSS Margins ]]>
                </title>
                <description>
                    <![CDATA[ By Kevin Powell CSS gets a bad rap for not behaving the way people expect. One of the things that throws people off the most are margins. They seem so simple, yet they have the potential to cause some really strange issues. For people just getting in... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/css-margins/</link>
                <guid isPermaLink="false">66d45f6673634435aafcefae</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS Margins ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 23 Jan 2020 16:25:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/01/Artboard-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Kevin Powell</p>
<p>CSS gets a bad rap for not behaving the way people expect. One of the things that throws people off the most are margins. They seem so simple, yet they have the potential to cause some really strange issues.</p>
<p>For people just getting into CSS, it's easily one of those things that can get you thinking "this is a stupid language that makes no sense!" </p>
<p>I see it everyday – both in the classroom as people try to figure out their spacing issues and in my <a target="_blank" href="https://youtube.com/kevinpowell">YouTube</a> comments sections as well.</p>
<p>In a way, margins are bit of a microcosm of CSS in general. CSS seems so simple with its <code>property: value</code> pairs, but as you progress with it, you realize that there is a lot going on.</p>
<p>Margins also seem so simple. Add some margin, and you add some empty space around that element. But then suddenly they behave a little differently in one situation than another, or you add some <code>margin-top</code> to a child element, and instead it's the parent that moves down.</p>
<p>Frustration ensues.</p>
<p>In this article, I hope to shed a little light on how margins work. We'll look at some of the common problems that happen, as well as simple solutions to those issues.</p>
<p>To go over all this, I'll be using examples from my <a target="_blank" href="https://scrimba.com/p/gresponsive?utm_source=dev.to&amp;utm_medium=referral&amp;utm_campaign=gresponsive_margins_5_minute_article">Responsive Web Design Bootcamp over on Scrimba</a>, which I pulled this simple layout from:  </p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ys0g9szfhgnobs611j1w.png" alt="CSS layout using margins and padding" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-are-margins-anyway">What are margins anyway?</h2>
<p>Before we really jump into the deep-end here, I want to make sure we all know what margins actually are! </p>
<p>I'm going to assume that we all know that margins are part of the box model, with margin being all the way on the outside, coming after the content itself, the padding and the border.</p>
<p>The MDN explains them really well (emphasis mine):</p>
<blockquote>
<p>The margin is the outermost layer, wrapping the content, padding and border as <strong>whitespace between this box and other elements</strong>. Its size can be controlled using margin and related properties.</p>
</blockquote>
<p>In other words, it's effectively empty space that we can use to create space between one box and another in our layout.</p>
<h2 id="heading-dealing-with-user-agent-stylesheets">Dealing with user-agent stylesheets</h2>
<p>Browsers come with a surprising amount of CSS by default, which we call <em>user-agent stylesheets</em>. These styles are the reason that, without any CSS on our part, an <code>&lt;h1&gt;</code> is bigger than an <code>&lt;h2&gt;</code>, and why the <code>&lt;body&gt;</code> has a margin on it that we tend to always remove.</p>
<p>These styles are important, but they also lead to one of the biggest issues that people run into with margins! Margins don't default to <code>0</code> on all of our elements, and this can cause all sorts of strange issues which we'll be exploring shortly.</p>
<p>Lists, blockquotes, paragraphs, and headings all have <code>margin</code> on them (among other elements). While sometimes they're only a slight inconvenience, the default margin on paragraphs and headings seems to be the one which causes most issues out of the box. </p>
<p>By default, the left and right margins of a text element are set to <code>0</code>, but they all come with a <code>margin-top</code> and <code>margin-bottom</code>.</p>
<p>I often tell people that those top and bottom defaults are roughly the same as the <code>font-size</code> of that element, since it's true for <code>&lt;p&gt;</code> as well as <code>&lt;h3&gt;</code> through <code>&lt;h6&gt;</code>. For <code>&lt;h1&gt;</code> it's actually <code>0.67em</code> and for <code>&lt;h2&gt;</code> it's <code>0.83em</code>. </p>
<p>This means that space exists between the elements on our page even if we have not explicitly set a margin. </p>
<p>We'll come back to these defaults in a second. </p>
<h2 id="heading-collapsing-margins">Collapsing margins</h2>
<p>Collapsing margins are where the headaches often start.</p>
<p>When two elements have <strong>vertical</strong> margins which touch each other, they effectively merge into one another. </p>
<p>It's already a strange behavior, and then add it to the fact that it's only for vertical margins (top and bottom), I get why people get confused and annoyed by them.</p>
<p>We can see this in action with the following example:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">40px</span>;
}

<span class="hljs-selector-class">.links</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">40px</span>;
}
</code></pre>
<p>To help illustrate what's happening here, the <code>.links</code> class is on the last paragraph (<code>&lt;p class="links"&gt;</code>) , which contains the two links inside it.</p>
<p>When people do something like this, they expect the margin between the middle paragraph and the links below it to be 80px (<code>40px</code> + <code>40px</code>), but in reality, it's 40px. The two margins are touching each other, so they merge into one another.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/8durzpm9lbaqs5384a8z.png" alt="Paragraph and links with 40px space between" width="600" height="400" loading="lazy"></p>
<p>To push it even more, let's give our <code>&lt;p&gt;</code>s' a  <code>margin-bottom</code> to <code>100px</code>:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">100px</span>;
}

<span class="hljs-selector-class">.links</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">40px</span>;
}
</code></pre>
<p>Again, the two margins don't add together, they collapse into one another, so the total space here is <code>100px</code>. </p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/wyzg6p0e4hmhb6k56o3c.png" alt="Paragraph and links with 100px space between" width="600" height="400" loading="lazy"></p>
<h3 id="heading-this-is-a-good-thing">This is a good thing</h3>
<p>In cases like this, it's actually a good thing, though. If there are several elements with different margins, there is no need to add the margins together to see how large the gap between the elements is because we can rely on the fact that <strong>the larger margin always wins</strong>.</p>
<p>We often don't even think about it, it just works the way we expect it to work.</p>
<h3 id="heading-when-its-not-a-good-thing">When it's not a good thing</h3>
<p>That said, one instance where margin collapse causes all sorts of confusion is when the first child within an element has a <code>margin-top</code> that merges with the parent's <code>margin-top</code>.</p>
<p>Let's look at that same screenshot again:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/wyzg6p0e4hmhb6k56o3c.png" alt="Paragraph and links with 100px space between" width="600" height="400" loading="lazy"></p>
<p>There is a white space between the top of the viewport and the black box. That's not from the body (it's much bigger than the <code>8px</code> margin the body would have). </p>
<p>Care to guess where it's coming from?</p>
<p>It's actually coming from the <code>&lt;h1&gt;</code> at the top of that black box.</p>
<p>Remember when I mentioned that the <em>user-agent stylehsheets</em> can do some odd things?</p>
<p>To help explain exactly what's happening here, let's add a much bigger <code>margin-top</code> to the <code>h1</code>. </p>
<pre><code class="lang-css"><span class="hljs-selector-class">.card</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#000</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">560px</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}

<span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">100px</span>;
}

<span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">100px</span>;
}

<span class="hljs-selector-class">.links</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p>I see people do this all the time, trying to push the title down <em>within</em> its parent. However, rather than working as expected, we get a giant space on top of the entire card!</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/qho6vjkt5y1m0ugp67mq.png" alt=" h1 with collapsed margin" width="600" height="400" loading="lazy"></p>
<p>This is because the <code>margin-top</code> on the <code>&lt;h1&gt;</code> merges with the <code>margin-top</code> on the parent element. </p>
<p>There is nothing separating the top of the child and the parent in this case. So when we add <code>margin-top</code> to the child, it touches the parent's <code>margin-top</code>. And, as we saw above, when two margins touch one another, they merge into a single margin.</p>
<p>So while we are giving the margin to the child, it's being applied to the parent. </p>
<p>This is why people hate CSS.</p>
<p>Similarly, in the code above we gave all paragraphs a <code>margin-bottom</code>. That margin on the <code>p.link</code> elements touches the <code>margin-bottom</code> of the <code>.card</code> element, which means that the two merge together and the margin affects the <code>.card</code> element instead of the links.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/diln7vboovivmqugvv45.png" alt="Card element with collapse margin" width="600" height="400" loading="lazy"></p>
<p>Although this isn't causing an issue for the site we are currently creating, it could cause problems if we later decided to add further elements to the page.</p>
<h2 id="heading-the-problem-is-were-using-margin-for-the-wrong-purpose">The problem is, we're using <code>margin</code> for the wrong purpose</h2>
<p>If I want space between the top of the <code>.card</code> element and the children inside it, I shouldn't be using <code>margin</code> anyway. </p>
<p>Beginners often get mixed up between <code>margin</code> and <code>padding</code>. My general rule of thumb is if you want empty space, use <code>margin</code>. If you want more background, use <code>padding</code>.</p>
<p>In this case, we want our <code>.card</code> to have more background, so we shouldn't be adding a <code>margin</code> to its children. Instead we should add <code>padding</code> to that element itself.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/enyvexftfy8h4ji7h8h1.png" alt="Result of adding padding to the parent element" width="600" height="400" loading="lazy"></p>
<p>In the image above, we can see the padding and the margin. The <code>&lt;h1&gt;</code> on top still has a margin, but it's no longer merging with the <code>.card</code> because the <code>padding</code> has added in a buffer. This prevents the <code>.card</code>'s and <code>h1</code> margin from touching one another.</p>
<p>As the padding adds sufficient space between the <code>&lt;p&gt;</code>s and the <code>&lt;h1&gt;</code>s, we can now remove the margins we previously added to them.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/4ukoaipasfd8ahal4796.png" alt="Site with larger margin-bottom on last child element." width="600" height="400" loading="lazy"></p>
<h2 id="heading-margins-dont-always-collapse">Margins don't always collapse</h2>
<p>There are some exceptions to collapsing margins. The direct descendants of grid and flex parents do not have collapsing margins. </p>
<p>Cue the ?.</p>
<p>But there is a bit of a workaround for this as well, which brings us full circle back to those user agent-stylesheets we talked about at the start.</p>
<h2 id="heading-there-is-an-easy-way-to-avoid-even-thinking-about-collapsing-margins">There is an easy way to avoid even thinking about collapsing margins</h2>
<p>First off, there is my general rule of thumb that I talked about above:</p>
<ul>
<li>If you need empty space, use <code>margin</code></li>
<li>If you need more background, use <code>padding</code></li>
</ul>
<p>That will get you out of trouble most of the time. But let's add an extra rule to this that will help even more:</p>
<ul>
<li>Try to avoid <code>margin-top</code> except when you <em>really</em> need it</li>
</ul>
<p>This rule is in a bit of conflict with the user-agent-styles, which set a <code>margin-top</code> and <code>margin-bottom</code> to a bunch of elements, which is one reason I often will do something like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h1</span>,
<span class="hljs-selector-tag">h2</span>,
<span class="hljs-selector-tag">h3</span>,
<span class="hljs-selector-tag">h4</span>,
<span class="hljs-selector-tag">h5</span>,
<span class="hljs-selector-tag">h6</span>,
<span class="hljs-selector-tag">p</span>,
<span class="hljs-selector-tag">ul</span>,
<span class="hljs-selector-tag">ol</span> {
 <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1em</span> <span class="hljs-number">0</span>;   
}
</code></pre>
<p>It eliminates a lot of the issues that come from collapsing margins on their own, as well as differences in your layout when some places are using flex or grid and others are not.</p>
<p>(Note: if you inspect the code here on freeCodeCamp, you'll see they do something similar as well!)</p>
<p>It's not a perfect solution, and I often do use a little <code>margin-top</code> on certain subtitles or in specific situations where it's called for. But I'm doing it very intentionally instead of letting the user-agent-styles potentially get in the way in some unforeseen way.</p>
<p>These lessons are just a snippet of my much larger course on responsive web design. To continue this coding journey, <a target="_blank" href="https://scrimba.com/p/gresponsive?utm_source=dev.to&amp;utm_medium=referral&amp;utm_campaign=gresponsive_margins_5_minute_article">take a look at the course</a>. </p>
<p>In the course I cover an introduction to responsive web design, and dive into both flexbox and grid, all the while trying to show people how much fun CSS really is once you start to understand how it works. </p>
<p>Happy coding :)</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
