【问题标题】:HTML - Bootstrap - How to crop the center part of an imageHTML - Bootstrap - 如何裁剪图像的中心部分
【发布时间】:2015-04-12 04:58:32
【问题描述】:

我正在创建一个网站,我想根据图像的方向将图像裁剪为方形图像。我对 CSS 不是很熟悉,所以我不知道如何解决这个问题。

如果是横向图像 (800x500),那么我希望裁剪后的图像是这样的 (500x500):

如果是人像 (400x600),那么它应该裁剪掉图像的这一部分 (400x400):

我应该如何实现这一目标?最好是一种我可以与 Bootstrap 的“img-responsive”一起使用的方法,这样我就可以在需要时调整裁剪的大小。

谢谢,

【问题讨论】:

    标签: html css image twitter-bootstrap-3 crop


    【解决方案1】:

    @Állan Fidelis Toledo 的救星

    人们可能会发现在 css 'object-fit' 上使用 'contain' 来保持图像的纵横比很有用。 通过设置 max-height 它在 Bootstrap 4 中也很有用。适用于 Bootstrap 4 中的所有“col”类。

    .thumb-post img {
      object-fit: contain; /* keep aspect ratio */
      width: 100%;
      max-height: 147px;
      margin-bottom: 1rem;
      padding-right: 10px;
    }
    

    【讨论】:

      【解决方案2】:

      不确定您是否仅限于 CSS 方法,但 JavaScript 方法将有助于获取图像的尺寸并将其包装在带有 overflow:hidden 的 div 中。

      $width = $(".box img").css('width');
      $height = $(".box img").css('height');
      $max = (($width < $height) ? $width : $height);
      
      $(".box").css("width", $max);
      $(".box").css("height", $max);
      .box {
        margin: 5px;
        overflow: hidden;
        display: flex;
        justify-content: center;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      
      <div class="box">
        <img src="https://placehold.it/300x200">
      </div>

      【讨论】:

        【解决方案3】:

        @FljpFl0p 修复它[jsfiddle][1]

        [1]:https://www.bootply.com/92024,这里还有另一个答案How to automatically crop and center an image。谢了!

        如果您希望它具有响应性并使用引导程序 4。试试这个:

        CSS

        .thumb-post img {
          object-fit: none; /* Do not scale the image */
          object-position: center; /* Center the image within the element */
          width: 100%;
          max-height: 250px;
          margin-bottom: 1rem;
        }
        

        【讨论】:

          【解决方案4】:

          为 img 标签添加 img-responsive 类,这将缩放您的图像并保持宽度/高度比。如果您对结果不满意,我会尝试使用 Javascript。

          【讨论】:

          • img-responsive 只会将图像水平缩放到其容器的大小,对图像的高度没有限制。
          • 我猜你必须为此使用 Javascript。您可以使用 max-height 属性限制高度,但在您的情况下它是无用的。
          • 是的,使用 max-height 和 overflow:hidden 可以帮助我将图像裁剪为我想要的大小,唯一的问题是它始终是图像的顶部。
          • @FljpFl0p 如果你不修复,试试这个jsfiddle :D
          猜你喜欢
          • 2017-01-15
          • 2015-01-15
          • 1970-01-01
          • 1970-01-01
          • 2020-09-07
          • 1970-01-01
          • 1970-01-01
          • 2014-05-26
          相关资源
          最近更新 更多