html - 裁剪图像以填充具有相对于宽度的高度的父级

标签 html css

我试图通过裁剪而不是拉伸(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 .到目前为止,它正在处理肖像图像。请帮忙,谢谢。

percentage dimensions

最佳答案

删除 min-height: 100%.landscapeimg 已经有 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/

相关文章:

html - 如何选择 Angular 6 中的所有复选框?

javascript - 我的 href 链接按钮无法联机使用

html - 使 div 成为其内容的大小

javascript - bootstrap 与 fullpage.js 不相邻

css - 在 Material UI 中设置 Tab 指示器的边框

html - div 行之间无法追踪的空白

css - HTML object 标签给一行空间

html - 如何为移动 Jquery 网站修复 css 中的边框半径

css - 3x3 CSS 网格 : how to make center div the only one with a fixed height/width?

javascript - 隐藏 Div JQuery 后无法显示