Search code examples
htmlcssbackground-image

div background image only shows with hardcoded values


I want to set an image by creating a div with a background-image. This code works, but I don't like that it has hardcoded values for height and width. The percentage values just don't work and the image disappears. Is it possible to avoid putting the actual pixel height and width in case I want to change the image in the future and not have to put in new values?


//html

<div class='img'></div>


//css
.img {
    background-image: url('../images/istockphoto-1353553203-1024x1024.jpg');
    display:block;
    background-size: cover;

    width: 1200px;
    height: 1000px;

}

Solution

  • Try to define the min-height and max-height of the image. The percentage doesn't work for you because it cannot fill any parent element. Try to make the div bigger and add any parent to it. You can view your page in different screen sizes with your browser's "Inspect" function.