Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the top margin of the h1 element in the header does not work as expected

Tags:

html

css

I have made use of the html5 header tag and an h1 tag within it. After setting up the top margin property of the h1 element in my header to 0px, i manage to remove the top margin of the header, but i want the h1 element inside my header to have a top margin of around 15px.

Now when i try setting the top margin of the h1 element, it also creates a top margin for the header which i don't want.

Can someone help me out with this...?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link href="normalize.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">

    <title>Codename : ENT</title>
</head>
<body>
    <header>
        <h1>Site Title / LOGO</h1>
        <p>Site Tagline / Slogan / One liner.</p>
        <p></p>
        <nav></nav>
    </header>
    <div id="content_wrapper"></div>
    <footer>
    </footer>
</body>
</html>  

and CSS

header {
    background-color:#ff0
}

header h1 {
    margin-top:0;
    margin-left:15px
}

header p {
    margin-left:15px
}
like image 619
skywalker2909 Avatar asked Aug 04 '14 08:08

skywalker2909


People also ask

Why margin-top is not working in a tag?

This issue is known as Margin Collapse and happens sometimes between top and bottom margins on block elements. That's why the margin doesn't work on the p tag. To make it work here an option is to use padding-top on the p tag. And on the a tag the margin doesn't work because it's an inline element.

What is the default margin of H1?

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

Which margin property is used to set top margin of an element?

The margin-top property in CSS is used to set the top margin of an element. It sets the margin-area on the top of the element. The default value of the margin-top property is 0.


2 Answers

Use padding-top for h1 or header or use overflow:hidden for header

like image 135
Anon Avatar answered Jan 03 '23 17:01

Anon


The issue you are facing here is call collapsing margins

Here is an excerpt from this mozilla article:

Parent and first/last child

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

So I could fix this by adding a border to the header element - DEMO

header {
    border: 1px solid transparent;
}

or by clearence - DEMO

header {
    overflow: hidden;
}

or by adding padding - DEMO

header {
    padding: 1px;
}

... etc etc

like image 43
Danield Avatar answered Jan 03 '23 18:01

Danield