Search code examples
htmlcssimagecss-grid

How do I size a background image to fit the web page?


I'm relatively new to HTML/CSS but I wanted to try creating a login page to familiarize myself with the code. Below I have tried to create a hero image that is responsive and allows me to see the content on top of it. My end goal being a box in the center asking for an email and password.

How do I get the background image to size correctly and not cause the site to be scrollable? Also not quite sure on the gridding or if it is the causing issue.

HTML:

<div class="hero-image">
    <div class="grid-container">
        <div id="top">1</div>
        <div id="lefts">2</div>
        <div id="insert">
            <form>
                <label for="email">Email</label>
                <input type="email" id="email" placeholder="Enter Email">
                <label for="password">Password</label>
                <input type="password" id="password" placeholder="Enter Password">
            </form>
        </div>
        <div id="rights">4</div>
        <div id="bottom">5</div>
    </div>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}
body{
    height: 100%;
}


.hero-image {
    background-image: linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)),url("Background.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    height: 50%;
}

.grid-container:nth-child(odd){

}

.grid-container {
    display: grid;
    grid-auto-columns: minmax(150px, auto);
    grid-auto-rows: minmax(300px, auto);
    grid-gap: 5px;
    grid-row: auto;
    grid-column: auto;
}

#top {
    grid-column: span 3;
    grid-row: span .75;
    color: green;
}

#lefts {
    grid-column: span 1;
    grid-row: span 1;
}
#insert {
    height: 100%;
    width: 100%;
    grid-column: span 1;
    grid-row: span 1;
}

#rights {
    grid-column: span 1;
    grid-row: span 1;

}

#bottom {
    grid-column: span 3;
    grid-row: span 2;
}

#password {
    text-align: left
}

Again very sorry as this was more or less last resort I've tried checking tutorials and documentation for the past 5 hours being still confused.


Solution

  • Use an inline style on the .hero-image class. You should avoid adding images in css as much as possible. For gradients/overlays, its best to use pseudo elements. You will have to add position: relative & a z-index to form so the overlay wont appear over the top of the div

    <div class="hero-image" style="background-image: url('Background.jpg);">
    </div>
    
    .hero-image {
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center center;
      height: 50%; 
      position: relative;
    }
    .hero-image::after{
         content: '';
         position: absolute;
         top: 0;
         right: 0;
         bottom: 0;
         left: 0;
         background: linear-gradient(180deg, transparent, rgba(0,0,0,0.3), 
         rgba(0,0,0,0.6), rgba(0,0,0,0.8));
    }