How to keep aspect ratio of background image?

I tried to see other answers, but didn't help. My background is dynamic, so the size of the images will change, so I need to keep the proportions so that the whole image is visible. here is my CSS:

.image_submit_div { border: 1px solid #ccc; display: inline-block; padding: 20px 50px; width: 55%; height: 320px; cursor: pointer; background: url('something.jpg'); /* this changes */ margin: 0 0 25px; 

}

HTML

 <label for="id_image" class="image_submit_div"> 

At the moment, depending on the image, sometimes it is cropped. I want the image to be scaled down so that it can be seen completely. Any idea?

+14
css
source share
2 answers

Use background-size: cover; to cover the whole element while maintaining the aspect ratio:

 .background-1, .background-2, .background-3 { /* Set the background image, size, and position. */ background-image: url('//via.placeholder.com/350x150'); background-size: cover; background-position: center; /* Or, use the background shortcut. */ background: url('//via.placeholder.com/350x150') center/cover; margin: 20px; border: 1px solid rgba(0, 0, 0, 0.3); } .background-1 { width: 300px; height: 200px; } .background-2 { width: 200px; height: 50px; } .background-3 { width: 100px; height: 200px; } 
 <div class="background-1"></div> <div class="background-2"></div> <div class="background-3"></div> 

If you want to display the entire image while maintaining the aspect ratio, use background-size: contain; instead:

 .background-1, .background-2, .background-3 { /* Set the background image, size, position, repeat, and color. */ background-image: url('//via.placeholder.com/350x150'); background-size: contain; background-position: center; background-repeat: no-repeat; background-color: #fbfbfb; /* Or, use the background shortcut. */ background: #fbfbfb url('//via.placeholder.com/350x150') no-repeat center/contain; margin: 20px; border: 1px solid rgba(0, 0, 0, 0.3); } .background-1 { width: 300px; height: 200px; } .background-2 { width: 200px; height: 50px; } .background-3 { width: 100px; height: 200px; } 
 <div class="background-1"></div> <div class="background-2"></div> <div class="background-3"></div> 
+22
source share

Use background-size:contain; if you want to see the whole image and stretch it to the entire width or height (depending on the aspect ratio of the image) div.

But if you want to cover the entire div with a background image and don’t mind that the image is cropped, use background-size:cover; .

 .image_submit_div { border: 1px solid #ccc; display: inline-block; padding: 20px 50px; width: 55%; height: 320px; cursor: pointer; background: url('http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg'); /* this changes */ margin: 0 0 25px; background-repeat:no-repeat; background-position:center; background-size:contain; } 
 <label for="id_image" class="image_submit_div"> 
+8
source share

All Articles