Search code examples
htmlcssbackground-imagescale

Background image full width and height


I'm setting up a banner for a website. The banner is consisting of an image, and some text on top of it, here's the code :

<div class="banner_div">
<style>
    .banner_div{
        background-image: url(/images/banner.jpg);
        width: 100%;
        height: 100%;
        background-size: contain;
    }
</style>
<p class="banner_text">Line 1</br>Line 2</p>
</div>

What I need is for the image to cover the full width of the screen (even if the screen is wider than the image, in which case the image should strech) and the height of the div to scale accordingly so the image is fully displayed. How can I achieve this ? I tried every property of background-size but it didn't work...

Edit : the current problem is that the height scales tho the one of the text


Solution

  • Try the following solution:

    body, html {
      margin:0;
      padding:0;
    }
    .banner_div {
      background-image: url(http://placehold.it/100x100);
      position:absolute;
      top:0;
      left:0;
      right:0;
      bottom:0;
      background-size:cover;
      background-position: center;
    }
    <div class="banner_div">
      <p class="banner_text">Line 1</br>Line 2</p>
    </div>