Reputation: 563
This is the code:
<html>
<head>
<title>The CSS Box Model</title>
</head>
<body>
<section>
<h1>An h1 inside of a section</h1>
</section>
</body>
</html>
So far what I know is that there is a Box Model. And each element is made of the Box Model. The Box Model has 4 parts: content, padding, border and margin. So in this part of the code:
<section>
<h1>An h1 inside of a section</h1>
</section>
The section's content is actually the whole box of the h1 that represents it + its margin (of the h1). Is that the case?
Upvotes: 3
Views: 1108
Reputation: 559
Margin is not considered the part of the element because of its strange behavior, margin collapse
so, what basically margin collapse is.
margin-bottom: 50px
, and the next one has a margin-top: 50px
, the space between them will be 50px
and not 100px
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
In the above code, the margin of the child
element is not part of it but, it will be the part of the parent
element width.
Also, Margin will collapse any time parent and first child element touch each other. So, if the first child in an element has a margin-top: 50px
and the parent is margin-top:70px
, they will merge and create a total margin space of 120px
.
We can add padding to the parent to prevent the parent’s margin from merging with the child’s.
.parent{
margin-top: 100px;
padding:40px;
background-color: green;
}
h1 {
margin-top: 50px;
margin-bottom: 40px;
background-color: red;
}
h2 {
margin-top: 40px;
background-color: blue;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="parent">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
</div>
</body>
</html>
Upvotes: 1
Reputation: 723578
Margins are not considered a part of an element. They are, however, considered a part of the element's box, where the box model is concerned. As far as the HTML DOM is concerned, the content of the section consists of the h1 element (there's also inter-element whitespace but that's just hair-splitting you don't need to worry about right now). In the layout, the section's box contains the h1's box in much the same way. That's just about the simplest way to put it.
However, since margins have very peculiar behaviors (see Ilya Streltsyn's comment referring to margin collapsing) compared to padding and borders which are generally simpler and more predictable, it's not really possible to think of margins in terms of being part of an element, much less part of the element's parent's content. For instance, does "content" refer to whatever's physically inside the parent as you see it in the layout, or does it refer to any part of any of the parent's child elements? What of the portions of those child elements that collapse with, or overflow, the parent? This is where things get confusing really quickly.
Upvotes: 6