【问题标题】:Fill a div with a reponsive <img> and position centrally [duplicate]用响应式 <image> 填充 div 并居中定位 [重复]
【发布时间】:2016-11-01 12:20:30
【问题描述】:

如何确保容器内的img 居中并从移动设备正确缩放到桌面?这是demo on Codepen。扩展到移动设备以更好地了解问题

HTML

<div class="image-container">
  <img src="https://placeimg.com/470/310/people" alt="" /> 
</div>

CSS

.image-container{
 width: 100%;
 height: 500px;
 max-height: 500px;
 background: red;
 overflow: hidden;
 text-align: center;
 position: relative;
 display: block;
 }

 img{
 height: auto;
 width: 100%;
 max-width: 100%;
 position: absolute;
 top: -50%;
 left: 0;
}

我问这个是因为图像在移动设备上失去了高度并且看起来不正确。我有点像`background-size:cover。我希望图像完全填满容器

【问题讨论】:

    标签: html css responsive-design


    【解决方案1】:

    要在 div 中水平和垂直居中图像,您可以设置 top: 50%left: 50%,然后添加 transform: translate(-50%, -50%)

    要使图像响应,您可以使用max-width: 100%,默认高度为自动。

    .image-container {
      width: 100%;
      height: 500px;
      background: red;
      overflow: hidden;
      position: relative;
    }
    img {
      max-width: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    <div class="image-container">
      <img src="https://placeimg.com/470/310/people" alt="" />
    </div>

    如果您不想使用relative/absolute 位置但要保持img 响应,则可以使用Flexboxheight: 100% 一起使用object-fit: contain

    .image-container {
      width: 100%;
      height: 500px;
      background: red;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    img {
      max-width: 100%;
      object-fit: contain;
    }
    <div class="image-container">
      <img src="https://placeimg.com/470/310/people" alt="" />
    </div>

    如果您希望img 的行为类似于background-size: cover,一种方法是将object-fit: coverheight: 100%width: 100% 一起使用

    body,
    html {
      margin: 0;
      padding: 0;
    }
    .image-container {
      width: 100%;
      height: 500px;
      background: red;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <div class="image-container">
      <img src="https://placeimg.com/470/310/people" alt="" />
    </div>

    【讨论】:

    • 老实说,我对 flexbox 还很陌生。我在我的 Bourbon 网格中使用了你的代码,但它不起作用。
    【解决方案2】:

    您可以添加margin:0 auto; 以水平居中对齐。 Remove width:100% 因为这将拉伸图像的宽度,除非你想要它。保持height:autowidth调整。

    .image-container{
      width: 100%;
      height: 500px;
      max-height: 500px;
      background: red;
      overflow: hidden;
      text-align: center;
      position: relative;
      display: block;
    }
    
    img{
     height: auto;
     max-width: 100%;
     margin:0 auto;
    }
    <div class="image-container">
      <img src="https://placeimg.com/470/310/people" alt="" />
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2015-06-26
      • 2014-05-19
      • 2014-03-06
      • 2021-09-07
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多