I'm making a page that will just display an SVG image, and here are the requirements:
The CSS...
body { background: url(/path/to/image.svg); background-size: cover; }
...works almost perfectly except that when the browser window becomes too narrow it tiles instead of cropping/clipping.
Here are some screen shots (please ignore the artifacts left by dabblet):
Here the window is close to the aspect ratio of the original image
Here the window is "shorter" than the aspect ratio, and the image is cropping (as desired).
Here the window is "narrower" than the aspect ratio, but instead of cropping, the image is tiling (undesired).
Here are some thoughts that I had...
Here's the dabblet that I was working with... http://dabblet.com/gist/6033198
We can do this purely through CSS thanks to the background-size property now in CSS3. We'll use the html element (better than body as it's always at least the height of the browser window). We set a fixed and centered background on it, then adjust it's size using background-size set to the cover keyword.
cover tells the browser to make sure the image always covers the entire container, even if it has to stretch the image or cut a little bit off one of the edges. contain , on the other hand, says to always show the whole image, even if that leaves a little space to the sides or bottom.
The background-size CSS property sets the size of the element's background image. The image can be left to its natural size, stretched, or constrained to fit the available space.
Use background-size property to cover the entire viewport The CSS background-size property can have the value of cover . The cover value tells the browser to automatically and proportionally scale the background image's width and height so that they are always equal to, or greater than, the viewport's width/height.
After some trial-and-error, this is what I found.
Adding (to the original CSS):
html { height: 100% }
delivered exactly what I was looking for in the original spec.
Additionally, if I wanted the image to be center when it was cropped, I could use:
html { background: url(path/to/image.jpg) no-repeat center center fixed; background-size: cover; }
Lastly, if I wanted it to be centered, always maintain the aspect ratio, but NOT be cropped (i.e., some whitespace is OK) then I could do:
body { background: url(/path/to/image.svg) no-repeat center center fixed; background-size: contain; }
For me I had all other properties set except background-attachment:fixed
. I had experienced the same issue on a site of mine for ages, one of the most elusive and infuriating bugs I've ever come across, but adding this to the html
element seems to have finally solved it for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With