1

Even after setting the margin and padding on the body and html to 0, the background color on my header element doesn't fill up the whole top part of the website.

This is what it looks like:

enter image description here

Here is my html and css

<body>
        <header>
                <h1>Test Website</h1>
        </header>
        <main>
                <div>
                        <h2 >Test Website</h2>
                </div>
        </main>
    <body>
    html, body{
        background-color: #ffffff;
        font-family: Nunito, sans-serif, serif;
        font-size: 28px;
        margin:0px;
        padding:0px;
        text-align:center;
    }

    header{
        background-color: rgb(3, 231, 231);
        margin: 0px;
        padding: 0px;
        height: 100%;
    }
Temani Afif
  • 245,468
  • 26
  • 309
  • 415

3 Answers3

0

Giving margin 0 to a parent element does not means that a child does not still have default, browser-given margins.

Elements like H1, H2, P, etc... inherit the document's User Agent Stylesheet, which for hystorical styling reasons are given by the browser those default margins. Or paddings, like for UL, OL, etc...

Set the margin to 0 to any such element.
Use padding instead - if you want to add space to your block-level elements.

Inspect in developer console to figure out which elements are given such a margin.

One nifty and quick CSS reset I use is:

* {
  margin: 0;
  box-sizing: border-box; 
}
/* applies to all elements on the page */
/* and no, it's not slow. 2022. */

A quick rule of thumbs:
use margin if you really, really know what you're doing (like i.e: handling the position of a CSS grid or flex child element). Use paddings instead.
Use box-sizing: border-box; to change the box sizing model, so that, while using the cool paddings, you don't have to account in the elements width/height (will be subtracted automatically by the browser).

Find out more on each of those properties on MDN.

Additional reading on collapsing margins: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • You misrepresent the contents of that MDN Web Docs tutorial article. It provides information on how to successfully use margins; it does not make the case for "why to avoid margins at all cost". – Sean Dec 31 '21 at 02:17
  • @Sean thank you, you're right. But my point is clear anyways. Edited. – Roko C. Buljan Dec 31 '21 at 11:27
0

The top margin of the <h1> element is pushing the <header> element down. You can either set a padding-top on the header element, or remove the margin from the heading.

Read more about margin collapsing.

Sean
  • 6,873
  • 4
  • 21
  • 46
-1

That is caused by the margin on you h1 element.

Try adding this to your CSS as well

h1 {
    margin: 0;
}
Thalles Cezar
  • 169
  • 1
  • 4