Home > other >  background-color doesn't fill up the whole thing
background-color doesn't fill up the whole thing

Time:12-31

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%;
    }

CodePudding user response:

That is caused by the margin on you h1 element.

Try adding this to your CSS as well

h1 {
    margin: 0;
}

CodePudding user response:

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.

CodePudding user response:

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 why to avoid margins at all cost: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

  • Related