Home > Software engineering >  Give a resizable background-image a full width
Give a resizable background-image a full width

Time:10-28

I'm working on a project where I have to give a background-image a full width. The image should become larger as I make the screen larger, and smaller as I make the screen smaller.

This is my code at the moment. It's a footer decoration:

.footerDeco {
  background-image: url(../resources/image_geometry_2.svg);
  background-repeat: no-repeat;
  height: 160px;
  background-size: cover;
}

The background-size: cover makes the image adapt to full width, but the height of the image remains 160px no matter what. If I make the height larger, then it's a problem because it doesn't shrink back proportionally as the screen becomes smaller.

I have tried giving it a height auto or a height 100% expecting the height to change proportionally to the width. (I do understand this height is the height of the footer container, but I don't know how to change it otherwise).

I know it would be much easier to use an img tag. But the demands of the project and good practice insist that since this is a decoration, I should use the background-image property. Is it possible? Thanks!

P.S.: There are similar questions that have been answered here, but none of them (as far as I can tell) solve the problem of the image resizing past the constant container height of 16px.

CodePudding user response:

To make the height change proportionally to the width, you can use vw to specify the height, for example:

.rooterDeco {
    height: 20vw;
}

CodePudding user response:

maybe for a size of 100% it will work

 background-size: 100% 100%;

using percentage makes the element one size relative to the size of the parent element.

CodePudding user response:

You can use aspect-ratio.

.footerDeco {
  aspect-ratio: 16 / 9;
  background: url(https://www.fillmurray.com/g/300/200);
  background-size: cover;
}
<div ></div>

  • Related