【问题标题】:Resize image into square div keeping aspect ratio将图像大小调整为方形 div 保持纵横比
【发布时间】:2018-02-24 15:36:58
【问题描述】:

我需要在我的应用程序中将图像插入到给定大小的方形 div 中,并且我希望它们显示完整,而不裁剪任何部分。目前我有一个javascript代码,如果图像是纵向(高度>宽度),则将高度设置为100%,宽度设置为自动,如果是横向(宽度>高度),则将宽度设置为100%,高度设置为自动

http://jsfiddle.net/z7L6m2sc/583/

这是我试图重现我的代码的链接(它在 erb 和咖啡中,因为我正在开发一个 rails 应用程序,我不知道为什么但是图像不在 div 内居中(在我的应用程序中这个代码效果很好!)

这是我在 Rails 中的代码

ERB

<div class="img">
  <% if i.insertion_images.length > 0 %>
    <%= image_tag(i.insertion_images[i.first_img].image.url(:medium), class: 'last_img')%>
  <% end %>
</div>

这是咖啡

$('.last_img').on 'load', ->
      natHeight = $(this).get(0).naturalHeight
      natWidth = $(this).get(0).naturalWidth
      if (natWidth > natHeight)
        $(this).css( 'width','100%')
        $(this).css( 'height','auto')
      else #if (natWidth < natHeight)
        $(this).css( 'height','100%')
        $(this).css( 'width','auto')

这是scss

img {
      width: 200px;
      height: 200px;
      overflow: hidden;
      position: relative;
      last_img {
        position: absolute;
        top: -9999px;
        bottom: -9999px;
        left: -9999px;
        right: -9999px;
        margin: auto;
      }
    }

我开始在布局中使用 flex,所以我的问题是,是否可以使用 flex 组件实现这种行为?也许没有所有 JS 代码和 css 中的 -9999

谢谢

【问题讨论】:

    标签: ruby-on-rails image flexbox scaling centering


    【解决方案1】:

    如果您不介意将图像设置为背景,可以使用 CSS 来实现。

    .bg-image{
      height: 300px;
      width: 300px;
      background-color: red;  
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center; 
      display: inline-block;
    }
    <div class="bg-image img-1" style="background-image: url(http://s.hswstatic.com/gif/landscape-photography-1.jpg)"></div>
    <div class="bg-image img-2" style="background-image: url(https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg)" ></div>

    【讨论】:

      【解决方案2】:

      您可以在.image-resize 上使用max-height: 100% 和max-width: 100%,我相信它会给您带来您想要的结果。如果你想安全,你也可以添加width: auto和height: auto。

      .img-container{
        height: 300px;
        width: 300px;
        overflow: hidden;
        background:red;
        position: relative;
      }
      
      .image-resize {
        max-width: 100%;
        max-height: 100%;
        height: auto;
        width: auto;
      }
      <div class="img-container">
        <img src="http://s.hswstatic.com/gif/landscape-photography-1.jpg" class="image-resize"/>
      </div>
      <hr>
      <div class="img-container">
        <img src="https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg" class="image-resize"/>
      </div>

      【讨论】:

        猜你喜欢
        • 2013-06-26
        • 2012-04-15
        • 2015-04-18
        • 1970-01-01
        • 2012-05-01
        • 2012-11-15
        相关资源
        最近更新 更多