我试图通过裁剪而不是拉伸(stretch)来用图像填充 div 容器。我需要图像居中,即使它是横向或纵向的。
#main-container {
display: flex;
width: 400px;
height: 200px;
background: green;
}
.img-container {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
margin: 1px;
width: 133px;
/* padding-bottom: calc(33.3% - 2px); */
height: 133px;
background: violet;
}
img {
/* margin-top: 100%; */
flex-shrink: 0;
min-width: 100%;
min-height: 100%;
}
.landscape {
/* max-width: 100%; */
max-height: 100%;
}
.portrait {
max-width: 100%;
}
.square {
max-width: 100%;
}
<div id="main-container">
<div class="img-container">
<img class="landscape" src="https://images.pexels.com/photos/371633/pexels-photo-371633.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
</div>
<div class="img-container">
<img class="portrait" src="https://i.pinimg.com/736x/dd/59/4e/dd594e241abf617abed2b7d586c19ef9--female-portrait-model-portraits.jpg?b=t">
</div>
<div class="img-container">
<img class="square" src="http://www.politicalmetaphors.com/wp-content/uploads/2015/04/blog-shapes-square-windows.jpg">
</div>
</div>
我需要将它应用于高度相对于宽度而不是像素的容器。但它不适用于 landscape images .到目前为止,它正在处理肖像图像。请帮忙,谢谢。
最佳答案
删除 min-height: 100%
的 .landscape
。 img
已经有 min-height: 100%
#main-container {
display: flex;
width: 400px;
height: 200px;
background: green;
}
.img-container {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
margin: 1px;
width: 133px;
/* padding-bottom: calc(33.3% - 2px); */
height: 133px;
background: violet;
}
img {
/* margin-top: 100%; */
flex-shrink: 0;
min-width: 100%;
min-height: 100%;
}
.landscape {
/* max-width: 100%;
max-height: 100%;*/
}
.portrait {
max-width: 100%;
}
.square {
max-width: 100%;
}
<div id="main-container">
<div class="img-container">
<img class="landscape" src="https://images.pexels.com/photos/371633/pexels-photo-371633.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
</div>
<div class="img-container">
<img class="portrait" src="https://i.pinimg.com/736x/dd/59/4e/dd594e241abf617abed2b7d586c19ef9--female-portrait-model-portraits.jpg?b=t">
</div>
<div class="img-container">
<img class="square" src="http://www.politicalmetaphors.com/wp-content/uploads/2015/04/blog-shapes-square-windows.jpg">
</div>
</div>
关于html - 裁剪图像以填充具有相对于宽度的高度的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740812/