幻灯片 div 是轮播的一部分,其中包含大小或纵横比不同的图像。如何在不损失质量的情况下将背景图像居中(无论大小如何)?我编写的代码非常适合普通尺寸的图像,但如果图像较小(30 像素 x 30 像素),它将被拉伸(stretch)以匹配 div 的宽度或高度。
<div class="slide"></div>
.slide {
width: 100%;
height: 400px;
background-image: url('./assets/img4.jpeg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
border: 1px solid red;
}
最佳答案
你可以使用一个容器(.imagecont
):
.container {
width: 10em;
border: 1px solid black;
}
.imagecont {
position: relative;
width: 10em;
height: 10em;
}
img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
max-width: 10em;
max-height: 10em;
margin: auto;
}
<div class="container">
<div class="imagecont">
<img src="https://google.com/favicon.ico">
</div>
<div class="imagecont">
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
</div>
可变宽度版本(尝试用鼠标调整容器大小)
.container {
border: 1px solid black;
width: 5em;
resize: horizontal;
-moz-resize: horizontal;
overflow: hidden;
}
.imagecont {
position: relative;
height: 10em;
max-width: 100%;
}
img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
}
<div class="container">
<div class="imagecont">
<img src="https://google.com/favicon.ico">
</div>
<div class="imagecont">
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
</div>
关于html - 如何在不损失质量的情况下将背景图像居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54496234/