pri*_*ain 0 html css image center scale
这是我的html代码
<div><img src="picture1.jpg" /></div>
<div><img src="picture2.jpg" /></div>
<div><img src="picture3.jpg" /></div>
Run Code Online (Sandbox Code Playgroud)
我的 div 容器有一定的固定尺寸:
div{
width: 400px;
height: 400px;
object-fit: cover;
overflow: hidden;
}
img{
height:100%;
width: 100%;
display: block;
}
Run Code Online (Sandbox Code Playgroud)
我想在 div 容器内尽可能多地显示图像的中间部分(并裁剪掉图像的其余部分)。因此,根据图像的尺寸,我想从图像的左右或顶部和底部裁剪一点。这样就可以显示图像中最大的正方形。该正方形应居中,当然也应相应缩放。
我之前尝试过很多,也读过很多帖子。比如这个。问题是,对于不同的图像尺寸,没有任何东西对我来说是并行的(请记住,我不想针对不同的图像调整代码)。我想要一个代码给所有人!
html 代码应保持原样。只需要调整 css 即可使其正常工作(所以我不想使用背景图像)。但我对最先进的 CSS 东西持开放态度。使用弹性布局或任何你想要的!
添加object-fit: cover;到图像以填充给定尺寸,同时不拉伸图像。还用于height: 100%; width: 100%;确保图像仅占据给定的空间。
默认情况下图像将居中。
img {
object-fit: cover;
width: 100%;
height: 100%;
}
/* for demonstration only */
div {
margin-bottom: 20px;
}
div:nth-of-type(1) {
width: 200px;
height: 50px;
}
div:nth-of-type(2) {
width: 200px;
height: 100px;
}
div:nth-of-type(3) {
width: 200px;
height: 200px;
}Run Code Online (Sandbox Code Playgroud)
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>Run Code Online (Sandbox Code Playgroud)