如何保持背景图片的宽高比? [英] How to keep aspect ratio of a background-image?
问题描述
我尝试查看其他答案,但没有帮助.我的背景是动态的,因此图像的大小会发生变化,因此我需要保持宽高比,以便可以看到整个图像.这是我的CSS:
I've tried to look at other answers but no help. My background is dynamic so the size of images will change, so I need to keep aspect ratio so the whole image is seen. here's 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 alot of it is cut off. I want the image to be downsized so it can be seen fully. Any idea?
推荐答案
使用 background-size: cover;
覆盖整个元素,同时保持宽高比:
Use background-size: cover;
to cover the entire 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>
如果要显示整个图像,同时保持宽高比,请使用 background-size: contain;
代替:
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>
这篇关于如何保持背景图片的宽高比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!