【问题标题】:Set a divs height to match the divs width when using a percentage and media query's for the width使用百分比和媒体查询作为宽度时,设置 div 高度以匹配 div 宽度
【发布时间】:2016-06-25 18:23:10
【问题描述】:

我有一个 div 网格,需要更改高度以匹配 div 的宽度。我已经习惯了媒体查询和 jquery 来实现这一点,但是在 jquery 运行之后,并非所有 div 的高度都相同。我在 jquery 中遗漏了什么吗?

jQuery

var setFeedItem = function () {
  console.log($(this).css('width'));
  $(this).css('height', $(this).width());
};

$('#feed .feed_item').each(setFeedItem);
$(window).resize(function () {
  $('#feed .feed_item').each(setFeedItem);
});

CSS:

.feed_item {
  overflow: hidden;
  margin: 0;
  padding: 0 !important;
  position: relative;
  float: left;
  height: 100px;
}
.feed_item img {
  width: 100%;
  height: 100%;
}
@media screen and (max-width: 2500px) {
  .feed_item {
    width: 10%;
  }
}
@media screen and (max-width: 2000px) {
  .feed_item {
    width: 12.5%;
  }
}
@media screen and (max-width: 1500px) {
  .feed_item {
    width: 20%;
  }
}
@media screen and (max-width: 1200px) {
  .feed_item {
    width: 25%;
  }
}
@media screen and (max-width: 900px) {
  .feed_item {
    width: 33.33333333%;
  }
}
@media screen and (max-width: 700px) {
  .feed_item {
    width: 50%;
  }
}
@media screen and (max-width: 480px) {
  .feed_item {
    width: 100%;
  }
}
@media screen and (max-width: 320px) {
  .feed_item {
    width: 100%;
  }
}

HTML:

<div id="feed">
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand3.jpg" /></div>
  <div class="feed_item"><img src="images/rand2.jpg" /></div>
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand4.jpg" /></div>
  <div class="feed_item"><img src="images/rand2.jpg" /></div>
  <div class="feed_item"><img src="images/rand1.jpg" /></div>
  <div class="feed_item"><img src="images/rand4.jpg" /></div>
  <div class="feed_item"><img src="images/rand3.jpg" /></div>
</div>
<div style="clear:both"></div>

可能是媒体查询干扰了 jQuery,但任何帮助都会很好,因为这会不断破坏我的布局。

【问题讨论】:

    标签: jquery html css css-float media-queries


    【解决方案1】:

    如果我理解正确,您想要方形响应块吗?在这种情况下,您不需要 jQuery。您可以在元素上使用 padding-bottom,为它们提供“响应式”高度。

    .feed_item{
      width:20%;
      background:red;
      padding-bottom:20%;
    }
    

    如果您想要这些块中的图像,缩放到.feed_item 的大小,您可以将position:relative 添加到.feed_item 并定位img 绝对值。看看这支笔:

    http://codepen.io/SamP/pen/GqrypX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2012-04-05
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多