Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit background image to div

I have a background image in the following div, but the image gets cut off:

 <div style='text-align:center;background-image: url(/media/img_1_bg.jpg);background-repeat:no-repeat;width:450px;height:900px;' id="mainpage" align="center"> 

Is there a way to show the background image without cutting it off?

like image 334
Rajeev Avatar asked Nov 20 '11 07:11

Rajeev


People also ask

How do you make a background image fill a div?

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

How do I fit a whole image into a div?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

How do I make the background image fit my screen CSS?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.


1 Answers

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain; 

To scale the background image to cover the whole div:

background-size: cover; 

JSFiddle example

There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.

like image 191
grc Avatar answered Oct 02 '22 02:10

grc