Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background-size contain, but don't scale up

I set my background image to contain:

.el {     background: url(path/to/img.jpg) no-repeat center center;     background-size: contain; } 

But that scales the image up. I want the image to never be bigger than its native dimensions, and only scale down when it won't fit at its native resolution.

Here's a demo: http://jsfiddle.net/6W3yh/


I'm looking for a solution in CSS only.
No JavaScript please.

like image 889
MegaHit Avatar asked Mar 12 '13 14:03

MegaHit


People also ask

What does background-size contain mean?

If the background-size is contain or cover : While preserving its intrinsic proportions, the image is rendered at the largest size contained within, or covering, the background positioning area. If the image has no intrinsic proportions, then it's rendered at the size of the background positioning area.

What is difference between cover and contain in background-size?

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.

How do I make my background-size responsive?

Here's how to create responsive background images with CSS: Use the background-size property to encompass the viewport. Give this property a cover value that will tell a browser to scale the background image's heights and width so that they always remain equal to or greater than the height/width of the device viewport.


2 Answers

Unfortunately, what you want to do isn't possible in CSS.

Your best bet is to set the background-size using Javascript. However, if you want the image to scale down if the container is smaller than it, you will have to be able to retrieve the image's natural height.

if ($('.el').height() < imageHeight) {   $('.el').css('background-size', 'contain'); } else {   $('.el').css('background-size', 'auto'); } 
like image 106
Bill Avatar answered Oct 06 '22 04:10

Bill


You could use Uncle Dave's Ol' Padded Box Technique for this. Here's a fiddle showing it in action.

div {     background: url(http://cdn4.iconfinder.com/data/icons/silent_night_icons/128/santa.png) no-repeat center center;     background-size: 100%;      width: 100%;     max-width: 128px;     height: 0;     padding-bottom: 100%; /* (Image Height / Image Width) * 100%; */ } 

The only problem is that you'll need to know the width of your image for this to work. If you're using a CSS preprocessor like Compass you could offload this work onto the processor instead of doing it manually. Look here for information on that.

like image 35
kpeatt Avatar answered Oct 06 '22 05:10

kpeatt