【发布时间】: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