I have
body {
background: url(images/background.svg);
}
The desired effect is that this background image will have width equal to that of the page, height changing to maintain the proportion. e.g. if the original image happens to be 100*200 (any units) and the body is 600px wide, the background image should end up being 1200px high. The height should change automatically if the window is resized. Is this possible?
At the moment, Firefox looks like it's making the height fit and then adjusting the width. Is this perhaps because the height is the longest dimension and it's trying to avoid cropping? I want to crop vertically, then scroll: no horizontal repeat.
Also, Chrome is placing the image in the centre, no repeat, even when background-repeat:repeat
is given explicitly, which is the default anyway.
Just add this one line:
vh is viewport height. This will automatically scale to fit the device' browser window.
Check more here: Make div 100% height of browser window
There is a CSS3 property for this, namely
background-size
(compatibility check). While one can set length values, it's usually used with the special valuescontain
andcover
. In your specific case, you should usecover
:Eggsplanation for
contain
andcover
Sorry for the bad pun, but I'm going to use the picture of the day by Biswarup Ganguly for demonstration. Lets say that this is your screen, and the gray area is outside of your visible screen. For demonstration, I'm going to assume a 16x9 ratio.
We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for some reason. We could set the
background-size
property to some fixed length, but we will focus oncontain
andcover
. Note that I also assume that we didn't mangle the width and/or height ofbody
.contain
This makes sure that the background image is always completely contained in the background positioning area, however, there could be some empty space filled with your
background-color
in this case:cover
This makes sure that the background image is covering everything. There will be no visible
background-color
, however depending on the screen's ratio a great part of your image could be cut off:Demonstration with actual code
Try this,
Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me
Here's what worked for me:
I'm not sure what you're looking for exactly, but you really should check out these excellent blog posts written by Chris Coyier from CSS-Tricks:
http://css-tricks.com/how-to-resizeable-background-image/
http://css-tricks.com/perfect-full-page-background-image/
Read the descriptions for each of the articles and see if they're what you're looking for.
The first answers the following question:
The second post's goal is to get the following, a "background image on a website that covers the entire browser window at all times. "
Hope this helps.