peckoski
peckoski

Reputation: 115

Why margin is included in my standard box model?

I have the following HTML

<div class="container">
        <div class="article">
            <h2>Article</h2>
        </div>
        <div class="blog">
            <h2>Blog</h2>
        </div>
    </div>

and this css

.container {
    width: 1200px;
}
.article {
    background-color: red;
    float: left;
    width: 600px;
}

.blog {
    background-color: blue;
    width: 600px;
    float: left;
}

now they are perfecly putted inside the parent because 2 x 600px = 1200px ( the parent's width ).

But if i put margin in blog

.blog {
    background-color: blue;
    width: 600px;
    float: left;
    margin: 20px;
}

then the layout is broken.

On the mozilla documentation is mentioned that

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model#the_standard_css_box_model

standard box model does not include the margin it self. So only padding and border. But i give not padding and border rto my blog div i give only margin and i expect the layout to not be broken and to have still actuil width of 600px.

Can somoene explain me what is happening here and why my layout is broken

Upvotes: 0

Views: 119

Answers (1)

Viira
Viira

Reputation: 3911

It is worth noting that margin will apply outside the borders of the element and padding will apply inside the element. To understand this better consider the following examples.

Margin

* {box-sizing: border-box;}
.parent {width: 200px; height: 220px; background: limegreen;}
.child {height: 200px; width: 100%; background: red; margin: 20px;}
<div class="parent">
  <div class="child">
    
  </div>
</div>

As you can see that the child element is parted way from its parent's initial position and creating a space around it.

Padding

*{box-sizing: border-box;}
.parent1 {width: 200px; height: 220px; background: limegreen;}
.child1 {height: 200px; width: 100%; background: red; padding: 20px;}
<div class="parent1">
  <div class="child1">
    
  </div>
</div>

Here the padding is applied inside the child element so it won't leave the parent's width

Upvotes: 1

Related Questions