【问题标题】:Image not centered when larger than viewport大于视口时图像不居中
【发布时间】:2018-09-27 20:43:03
【问题描述】:

当视口大于图像宽度时,图像居中,但当图像宽度大于视口宽度时,图像向左对齐而不是居中。我的目标是使图像始终被裁剪到视口的宽度并始终与中心对齐。

body,
html {
  margin: 0;
  padding: 0;
}

.crop {
  width: 100%;
  height: 50%;
  overflow: hidden;
  background-color: red;
}

#cropped-img {
  position: relative;
  height: 100%;
  display: block;
  margin: auto;
}
<div class="crop">
  <img id="cropped-img" src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg" />
</div>

【问题讨论】:

    标签: html css image alignment


    【解决方案1】:

    尝试为占据元素宽度100%的图片赋予可变值

    body,
    html {
      margin: 0;
      padding: 0;
    }
    
    .crop {
      width: 100%;
      height: 50%;
      overflow: hidden;
      background-color: red;
      text-align: center;
    }
    
    #cropped-img {
      position: relative;
      height: 100%;
      width: 100%;
      max-width: 100%;
      display: block;
      margin: 0 auto;
    }
    <div class="crop">
      <img id="cropped-img" src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg" />
    </div>

    【讨论】:

      【解决方案2】:

      你可以用 flexbox 实现你想要的:

      body,
      html {
        margin: 0;
        padding: 0;
      }
      
      .crop {
        overflow: hidden;
        background-color: red;
        display:flex;
        justify-content:center;
      }
      <div class="crop">
        <img id="cropped-img" src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg" >
      </div>

      【讨论】:

      • 这正是我想要的,谢谢。最后,我只是最终使用了带有 background-repeat: no-repeat 和 background-position: center 的背景图像,因为它更简单。
      【解决方案3】:

      没关系,我设法使用 background-image 属性获得了我需要的确切效果。如果其他人有兴趣,这是我使用的 HTML 和 CSS:

      HTML:

      <div class="crop"></div>
      

      CSS:

      body, html {
          margin:0;
          padding:0;
      }
      
      .crop {
          width: 100%;
          height: 500px;
          overflow: hidden;
          background-image: url("http://img1.jurko.net/wall/paper/donald_duck_4.jpg");
          background-repeat: no-repeat;
          background-position: center; 
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-20
        • 2012-09-21
        • 2011-08-19
        • 1970-01-01
        相关资源
        最近更新 更多