Search code examples
htmlcssimagecodepen

How do I add a background image that stretches the width of a webpage, using CSS?


But it's not that simple. I mean, how do I stretch an image to the width of a webpage, but only takes up 33% of the page (without looking distorted). I want to fill my webpage with 3 different background images that do this.

My question is, do I need to pre-edit the image to a certain length and width, so that they don't look distorted? Or am I just missing something?

I am studying freecodecamp and am trying to create a portfolio with three sections, each image used as a background to that particular section.

I've been researching in Stack Overflow, W3 schools, and tinkering around with different code snippets in codepen.io. I did try resizing the images with a photo editor, and then tried adding them to my page. They still look distorted and weird.

I'm afraid I'm stuck. Would anyone point me to a good resource or offer any insights?


Solution

  • 33% of window height?

    // HTML
    <div class="container">
        <div class="img first-background"></div>
        <div class="img second-background"></div>
        <div class="img third-background"></div>
    </div>
    
    // CSS
    .img{
        width: 100%;
        height: 33vh; // vh means ViewHeight, 33% of your window height
        background-size: cover;
        background-position: center;
    }
    
    .first-background{ background-image: url('/a-link-to-your-image.jpg') }
    .second-background{ background-image: url('/a-second-link-to-your-image.jpg') }
    .third-background{ background-image: url('/a-third-link-to-your-image.jpg') }