Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch and scale a CSS image in the background - with CSS only

Tags:

css

background

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?

like image 909
Fábio Antunes Avatar asked Jul 19 '09 15:07

Fábio Antunes


People also ask

How do you expand an image in CSS?

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.

How do I fit an image into a scale in CSS?

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.

How do I stretch a background image in HTML?

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.

How do you make a background image fill a div?

Use: background-size: 100% 100%; To make background image to fit the div size.


1 Answers

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.

like image 114
Vashishtha Jogi Avatar answered Oct 19 '22 07:10

Vashishtha Jogi