如何自动调整大小的大图像,使其适应较小宽度的
容器,同时保持其宽度:高度比例?
示例:stackoverflow.com - 当将图像插入到编辑面板上,并且图像太大无法适应页面时,图像会自动调整大小。
示例:stackoverflow.com - 当将图像插入到编辑面板上,并且图像太大无法适应页面时,图像会自动调整大小。
This was my solution. You will need to have the picture inserted twice. But it does not use js, and the img will resize to both width and height. You can click on 'run code snippet - full page', open dev console and resize window-width to see the responsive effect.
/* responsive width */
.responsivewidth{
background: lightsalmon;
height: 100px;
width: 50%;
}
/* Widthlimit */
.maxedbywidth {
background: navy;
height: 200px;
width: 100px;
}
.div1 {
max-height: 100%;
position: relative;
box-sizing: content-box;
/* Center: */
top: 50%;
transform: translateY(-50%);
}
.margerimg {
height: auto;
max-width: 100%;
opacity: 0;
}
.div2 {
height: 100%;
width: fit-content;
position: absolute;
top: 0;
/* Center: */
left: 50%;
transform: translateX(-50%);
}
.mainimg {
max-height: 100%;
max-width: 100%;
}
<div class="responsivewidth">
<div class="div1">
<img class="margerimg" src="https://via.placeholder.com/2000x1500" />
<div class="div2">
<img class="mainimg" src="https://via.placeholder.com/2000x1500" />
</div>
</div>
</div>
<div class="maxedbywidth">
<div class="div1">
<img class="margerimg" src="https://via.placeholder.com/2000x1500" />
<div class="div2">
<img class="mainimg" src="https://via.placeholder.com/2000x1500" />
</div>
</div>
</div>
这篇文章可能会对您有所帮助:
.square {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
}
img {
position: absolute;
max-width: 100%;
width: 100%;
height: auto;
top: 50%;
left: 50%;
transform: translate( -50%, -50%);
}
img.landscape {
height: 100%;
width: auto;
}
<div class="square">
<img src="https://unsplash.it/400/500" alt="Image" />
</div>
<div class="square">
<img src="https://unsplash.it/500/400" class="landscape" alt="Image" />
</div>
简单的CSS解决方案:如何将具有不同尺寸的图像适配到设置的容器中(2017年5月1日)
.square {
position: relative;
width: 441px;
height: 200px;
overflow: hidden;
border:1px solid black;
}
img {
max-width: 100%;
/* width: 100%;*/<----it stretch image and fit into the parent
height: auto;
/* transform: translate( -50%, -50%);*/<-----set vertically and horizontally center
}
img.landscape {
height: 100%;
width: auto;
}
<div class="square">
<img src="https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg" alt="Image" />
</div>