Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize background image in div using css [duplicate]

Tags:

html

css

Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

How can I stretch the images using css to fit into space required by div ?

<style type="text/css">    #contentMain {     margin-bottom: 5%;    margin-top: 10%;   margin-left: 10%;   margin-right: 10%;   background: url( /jQuery/mypage/img/background1.png ) }   #page1 {       background: url( /jQuery/mypage/img/background2.png )   }  </style>  
like image 789
user701254 Avatar asked May 17 '11 09:05

user701254


People also ask

How do I resize a background image in a div?

The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.

How do I change the background image size in CSS?

The background-size property is used to set the background image size using CSS. Use height and width property to set the size of the background image.

How do I stretch an image in CSS?

You can use the CSS background-size: cover; to stretch and scale an image in the background with CSS only. This scales the image as large as possible in such a way that the background area is completely covered by the background image, while preserving its intrinsic aspect ratio.


2 Answers

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

  • https://alligator.io/css/cropping-images-object-fit
like image 115
Alp Avatar answered Sep 29 '22 17:09

Alp


i would recommend using this:

  background-repeat:no-repeat;   background-image: url(your file location here);   background-size:cover;(will only work with css3) 

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

like image 29
Bram B Avatar answered Sep 29 '22 18:09

Bram B