Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max size for background image CSS

Tags:

html

css

image

I have a 70 by 50 px box and I have various images, (SVG files, so no size) I want to keep their aspect ratio, but some images are portrait and some are landscape sized. So I can do:

background-size: 70px auto;

and that will work for all the landscape icons. But it will stretch the portrait images and make them taller, so they will still have the correct aspect ratio but the top and bottom will be cut off.

is there some kind of background-max-size?

(alternatively, the only reason I'm using background image is because you can center align the image, horizontally and vertically, so the alternative is to find how to vertically align an img element within a li element.)

like image 970
Jonathan. Avatar asked Oct 29 '10 20:10

Jonathan.


People also ask

What size should a background image be?

Best background image size For background images, the best size is 1920 pixels wide x 1080 pixels high. This ideal ratio of 16:9 will fill the surface of the webpage without compromising the quality of the image. In terms of pixels per inch (ppi), the image should be at least 72.

What is CSS background-size?

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.

What does background-size 100% 100% mean?

Pretty sure background-size: cover; means the image will fill the element while maintaining its aspect ratio, while background-size: 100%; will just make the image fill 100% width of the element.

How do I limit a background image in CSS?

There are four different syntaxes you can use with this property: the keyword syntax ("auto", "cover" and "contain"), the one-value syntax (sets the width of the image (height becomes "auto"), the two-value syntax (first value: width of the image, second value: height), and the multiple background syntax (separated ...


2 Answers

It's not that hard doing that with CSS

  • 1st, please take a look at the Mozilla Specs for mixed units for background-size.
  • 2nd, please consider simply setting background-size: contain; (IE9+, Safari 4.1+, FF 3.0+, Opera 10+) and min/max-width/height for the container element.
like image 104
kaiser Avatar answered Oct 03 '22 00:10

kaiser


You can absolutely solve this problem without JavaScript using a combination of CSS3 background-size and media-queries. e.g.:

@media only screen and (max-width: 1000px) {
    #element {
        background-size: contain;
    }
}

Note that neither are supported in IE8 or below, so you should include fallbacks for old IE if you still support it.

like image 37
richardwestenra Avatar answered Oct 03 '22 00:10

richardwestenra