Eric Luo
Eric Luo

Reputation: 339

Why doesn't my code of collapsing margins work?

I wrote a simple html file to see how collapsing margins in css work, but I didn't get expected answer. First I'll show you my code:

<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <title>Collapsing Margins Testing</title>
    <style type="text/css">
        img {
            width: 300px;
            height: 300px;
        }
        
        .first {
            margin-right: 10px;
        }
        
        .second {
            margin-left: 20px;
        }
    </style>
</html>

<body>
   <img src="http://cdn.shopify.com/s/files/1/0051/4802/products/mona-2_1024x1024.jpg?v=1447180277" alt="github cat" class="first">
 
   <img src="http://cdn.shopify.com/s/files/1/0051/4802/products/mona-2_1024x1024.jpg?v=1447180277" alt="github cat" class="second">
  
</body>

I have set right margin of first image 10px and left margin of second image 20px respectively. I expect there to be 20px between the right of first image and left of second image as only bigger margin takes effect in collapsing margins. But when I inspect it in Google developer tools, the space between them are 30px(10px+20px). What's wrong with it? Or do I have a wrong understanding of collapsing margins?

Upvotes: 0

Views: 68

Answers (2)

sandiprb
sandiprb

Reputation: 502

  • Margin Collapsing works only on Block level elements.
  • Only top and bottom margins collapse, Right & Lefts don't.
  • An element's bottom margin and it's next elements top margins are collapsed.

It's very well explained here : https://css-tricks.com/what-you-should-know-about-collapsing-margins/

Just a tip : Google enough before posting questions!

Upvotes: 3

Kiran Dash
Kiran Dash

Reputation: 4956

Already pointed out by Sandip.

Margin collapsing works only on block level elements.

And also top and bottom margins collapse. Collapsing doesn't work for right and left margin.

Just for your clarity I edited your code snippet to replace img with block level elements and also replaced margin left and right with top and bottom so that you can see the margins collapse. The same will not happen for left and right margin.

<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <title>Collapsing Margins Testing</title>
    <style type="text/css">
        .first, .second  {
            width: 300px;
            height: 300px;
        }
        
        .first {
            margin-bottom: 10px;
            background: green;
        }
        
        .second {
            margin-top: 20px;
            background: yellow;
        }
    </style>
</html>

<body>
   <div class="first">aaa</div>
 
   <div class="second">bbb</div>
  
</body>

Upvotes: 1

Related Questions