html - 使用对象拟合和对象位置缩放、居中和裁剪图像

标签 html css

我想拍摄一张偶然的图像并让它按比例放大/缩小以使用父 div 的整个空间,同时保持其原始比例。我希望图像被裁剪(没关系,只要它在垂直和水平方向上都居中)。

我试过这段代码:

<div class="container" style="width: 800px">
  <div class="row">
    <div style="
          height:340px; 
          width: 100%; 
          overflow: hidden;
          border: 3px solid red;
          ">
      <img src="http://via.placeholder.com/500x500" style="
            object-position: center;
            object-fit: cover;
            ">
    </div>
  </div>
</div>

结果如下: Screenshot of result of original code. A div with a red outline as a photo of the Rolling Stones. The photo is aligned to the left and does not fill the div width wise. The background image can be seen through the div where the image does not fill it.

为什么它不能放大、居中和裁剪图像?

最佳答案

给图像一些尺寸(与没有定义尺寸的第二幅图像相比)

<div class="container" style="width: 800px">
  <div class="row">
    <div style="
      height:150px; 
      width: 250px; 
      overflow: hidden;
      border: 3px solid red;
      ">
      <img src="http://placekitten.com/400/200" style="
        width:100%;
        height:100%;
        object-position: center;
        object-fit: cover;
        ">
    </div>
  </div>
  <br>
  <div class="row">
    <div style="
      height:150px; 
      width: 250px; 
      overflow: hidden;
      border: 3px solid red;
      ">
      <img src="http://placekitten.com/400/200" style="
        object-position: center;
        object-fit: cover;
        ">
    </div>
  </div>
</div>

关于html - 使用对象拟合和对象位置缩放、居中和裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228684/

相关文章:

html - CSS 中的 wordpress 3.3 相对路径

html - 尝试使用 Node.js 提供带有图像的 html 页面时收到 GET 错误

html - 我的类 div 无法为我的文档设置样式。但是输入和标签是。我错过了什么?

javascript - 一个接一个地播放 Sprite 表

javascript - 使用 JavaScript 对象构造函数更改文本颜色

javascript - 在 Javascript 中,如何避免 createTextElement 方法中的 "escaping"?

javascript - 如何使用 Jquery 切换元素

javascript - 如何获取 if/else 语句的当前 url

css - Div的重叠

html - CSS/Div 容器边距问题