Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

margin on h1 element inside a div

Tags:

html

css

margins

I have a div container which has a h1 element within it:

<div id="header">
 <h1>Enlighten Designs</h1>
</div>

I have applied a margin-top,a margin-left and a margin-right to the header element. However the margin-top is not being applied to the header element box wrt to the containing div. Instead the top margin is being applied to the containing div. The left and right margins of the header are being applied to the header element box wrt the containing div.

The style rules for the div and header are as follows:

#header {
    background: blue;
    height: 150px;
}
h1{
    background: orange;
    margin-top:30px;
    margin-left: 10px;
    margin-right: 10px;
}

What is the reason for this behavior?

like image 676
newbie Avatar asked Jan 05 '14 15:01

newbie


People also ask

Can you put h1 inside a div?

HTML conventions prohibit Including a nested *div> within a [h1>). If you intend to put a paragraph into an H1 tag, you only must contain inline elements, that being'span' would contain a valid element, however a'span' paragraph isn't inline.

How do you put a margin inside a div?

Use the padding css property of the container (div) instead. Padding is the space inside and border of the element, while margin is the space outside the border of the element. Check out box model.

Does h1 have margin?

The <h1> on top still has a margin, but it's no longer merging with the . card because the padding has added in a buffer.

What is the default margin of h1?

For Google Chrome for example, it's 0.67em .


2 Answers

Your 'problem' is that margins in CSS will collapse onto eachother.

Read this awesome article explaining the concept, management summary:

In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.

In your case, specifically read the section "Collapsing Margins Between Parent and Child Elements" a few pages down. In your case, the following CSS 2.1 rule applies:

The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.

like image 115
Niels Keurentjes Avatar answered Oct 25 '22 06:10

Niels Keurentjes


Well, the solution is to add overflow: hidden; property to your header element.
Here JsFiddle.

like image 30
joseluisq Avatar answered Oct 25 '22 07:10

joseluisq