I want that my background image stretch and scale depending on the browser viewport size.
I've seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background
, not with an img
tag.
In that one an img
tag is placed, and then with CSS we tribute to the img
tag.
width:100%; height:100%;
It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I've tried this example the first one, but it didn't work out for me.
Is there a good method to do it with the background-image
declaration?
We can resize the image by specifying the width and height of an image. A common solution is to use the max-width: 100%; and height: auto; so that large images do not exceed the width of their container. The max-width and max-height properties of CSS works better, but they are not supported in many browsers.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover.
Use: background-size: 100% 100%; To make background image to fit the div size.
CSS3 has a nice little attribute called background-size:cover
.
This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too large.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With