html - 用于缩放的响应式图像高度和宽度百分比?

标签 html css ruby-on-rails ruby twitter-bootstrap

用户可以通过上传图片或输入文字来激发灵感。

查看

<% if inspiration.image.present? %>
  <div class="inspiration-image">
    <%= link_to image_tag(inspiration.image.url(:medium)), inspiration %>
  </div>
<% else %>
  <div class="panel panel-default">
    <div class="panel-body">
      <%= inspiration.name %>
    </div>
  </div>
<% end %>

CSS

// for images
.inspiration-image {
  display: inline;
  img {
    width: 50%;
    margin-top: 2.5px;
    margin-bottom: 2.5px;
    position: relative;
    overflow: hidden;
    vertical-align: top;
    height: 164px;
  }
}

// for text
.panel-default {
    box-sizing: border-box;
    border-style: none;
    position: relative;
    width: 50%;
    padding-bottom: 40%;
    overflow: hidden;
    background-color: #446CB3;
    border-radius: 0;
    display: inline-block;
    margin-bottom: 0px;
    border: 2.5px white solid;
}

//for text
.panel-body {
    color: white;
    width: 100%;
    height: 100%;
    text-align: center;
    position: absolute;
    font-size: 12px;
    justify-content: center;
    align-items: center;
    display: flex;
}

设置高度看起来不错:

enter image description here

但是,如果用户增大或减小屏幕尺寸,则图像会出现白色间隙,这是我希望在您的帮助下避免的情况:

enter image description here

根据 PASCAL 的问题更新

查看

<% if inspiration.image.present? %>
  <div class="panel panel-default" id="conditions">
    <div class="panel-body">
    </div>
  </div>
<% else %>
  <div class="panel panel-default">
    <div class="panel-body">
      <div class="white-link"><%= inspiration.name %></div>
    </div>
  </div>
<% end %>

CSS

#conditions {
  background-image: url('goal-setting-conditions.jpeg'); # instead of this image, which I just used to test if it works, how can I make the image reflect whatever inspiration it is: <%= link_to image_tag(inspiration.image.url(:medium)), inspiration %>
  background-size: cover;
}

这是我所希望的那种行为,无论屏幕大小图像和文本框的宽度和高度是否彼此相等:

enter image description here

最佳答案

使用 jQuery 将图像添加为父 div 中的背景。

jQuery(document).ready(function() {
    jQuery('.inspiration-image').find('img').each(function(n, image) {
        var image = jQuery(image);
        var thisurl = jQuery(this).attr('src');
        image.parents('.inspiration-image').css('background-image', 'url(' + thisurl + ')');
    });
});

在 CSS 中,将 div 上的 background-size 设置为覆盖。将图像隐藏在容器中。

.inspiration-image {background-size:cover;}
.inspiration-image img{opacity:0;}

关于html - 用于缩放的响应式图像高度和宽度百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37529345/

相关文章:

css - 在 CSS 中使图像适合浏览器大小

ruby-on-rails - Rails, Attachment_fu - 数据库存储附件的深拷贝

php - 如何在彼此相邻的两个单选按钮之间添加间距

jquery - 光滑的 slider 改变每张幻灯片的背景颜色

javascript - 如何在javascript中检测计算机电源是否暂停?

css - 你能在纯CSS中对图像进行keystone吗?

javascript - 在移动应用程序上滚动 iframe 在某个时候跳转到页面顶部

javascript - Bootstrap 下拉按钮高度不同

jquery - 根据 Ruby on Rails 中的当前数据库记录更改元素内容

ruby-on-rails - 尝试访问相关记录时未定义的方法