如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?
示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。
如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?
示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。
当前回答
<style type="text/css">
#container{
text-align: center;
width: 100%;
height: 200px; /* Set height */
margin: 0px;
padding: 0px;
background-image: url('../assets/images/img.jpg');
background-size: content; /* Scaling down large image to a div */
background-repeat: no-repeat;
background-position: center;
}
</style>
<div id="container>
<!-- Inside container -->
</div>
其他回答
我使用以下代码修复了此问题:
<div class="container"><img src="image_url" /></div>
.container {
height: 75px;
width: 75px;
}
.container img {
object-fit: cover;
object-position: top;
display: block;
height: 100%;
width: 100%;
}
我看到很多人都建议对象匹配,这是一个不错的选择。但是,如果您希望它也能在较旧的浏览器中工作,还有另一种方法可以轻松实现。
这很简单。我采用的方法是将图像放置在容器内,然后使用组合将其放置在中心:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
一旦它在中心,我给图像,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
这使图像获得对象拟合的效果:覆盖。
以下是上述逻辑的演示。
https://jsfiddle.net/furqan_694/s3xLe1gp/
此逻辑适用于所有浏览器。
此解决方案不会拉伸图像并填充整个容器,但会剪切部分图像。
HTML格式:
<div><img src="/images/image.png"></div>
CSS:
div {
width: 100%;
height: 10em;
overflow: hidden;
img {
min-width: 100%;
min-height: 100%;
}
检查我的答案,使图像响应-最简单的方法-
img{
width: 100%;
max-width: 800px;
}
您必须告诉浏览器您放置它的高度:
.example {
height: 220px; /* DEFINE HEIGHT */
background: url('../img/example.png');
background-size: 100% 100%;
background-repeat: no-repeat;
}