Image Stretching in Standard HTML

67 views Asked by At

Current Scenario: I'm building an application which takes an image and we set the background. I want to serve this application on mobile, desktop, and tablet devices.

Question:

I want to know the best way to stretch and show the image (without involving page lag). How do I incorporate fluid design?

Code:

I am currently trying something like this. Any improvements would help!

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
2

There are 2 answers

0
jan199674 On

It depends on the image:

If the image contains objects that can not easily be stretched like text, portraits, photos of animals or bicycles etc, you will need to preserve the original proportions ('aspect ratio').

Using only CSS there are 3 ways to scale and keep aspect ratio - none of them will work perfectly on all kinds of devices:

'contain' leaves a gap in either the sides OR in bottom and top depending on the size of the device:

body  {
    background: url(images/bg.jpg);
    background-repeat: no-repeat;
    background-position: center; 
    background-size: contain; 
}

'cover' keeps background filled, but zooms into the image depending on the size of the device - you will not not be able to see a part of the top and bottom of the image:

body  {
    background: url(images/bg.jpg);
    background-repeat: no-repeat;
    background-position: center; 
    background-size: cover; 
}

NOTE Background-size is CSS3 and will not work with older versions of IE

CSS2 - the third solution works in all browsers and behaves similar to 'background-size: contain;' - when the viewport of the device doesnt fit the image, you will experience a gap:

.img_width {
    width: 100%; 
    height: auto; 
} 
0
Dryden Long On

With modern browsers, the easiest way would be to use the following CSS:

#background-selector {
    background-image: url('image.jpg');
    background-size: cover;
}

EDIT OP has since added code to their post, so this may not be the most appropriate answer.