【问题标题】:Can I really not use table markup to get two elements to have equal height?我真的不能使用表格标记来让两个元素具有相同的高度吗?
【发布时间】:2015-07-22 21:51:01
【问题描述】:

好的,所以我知道使用table 进行布局是非常过时的。但是我需要使用两个并排的元素进行布局,一个具有通常的高度,如果它具有更高的内容,则可以增加,另一个包含图像。如果第一个长得更高,我希望有图像的那个长到与它的高度相匹配。

这是我可以通过良好的旧 table 轻松实现的目标。如何使用 div 做到这一点?

这是我想要做的:

.body {
  width: 748px;
  margin: 20px auto;
}
.breaker {
  margin: 20px 0;
  outline: 1px solid purple;
}
.poll {
  background: pink;
  width: 248px;
  height: 250px;
}
div.poll {
  float: left;
}
.story {
  float: right;
  width: 500px;
  background-size: cover;
}
<div class="body">

  <table class="breaker">
    <tr>
      <!-- This will have a variable height depending on content -->
      <td class="poll"></td>
      <!-- The height of this should match the height of .poll -->
      <td style="width:500px;background-image:url(http://lorempixel.com/output/animals-q-c-600-200-1.jpg);background-size:cover;">
      </td>
    </tr>
  </table>

  <div class="breaker">
    <!-- This will have a variable height depending on content -->
    <div class="poll"></div>
    <!-- The height of this should match the height of .poll -->
    <div class="story" style="background-image:url(http://lorempixel.com/output/animals-q-c-600-200-1.jpg)">
    </div>
  </div>

</div>

【问题讨论】:

  • 等高是 布局或 CSS 表格布局的原生特性之一,请参阅这个简化的演示 - jsfiddle.net/LLy1sLhq

标签: html css tablelayout


【解决方案1】:

display: table-cell 应用于两者并删除float

div.poll {
    display: table-cell;
    /* other styles */
}

.story {
    display:table-cell;
    /* other styles */
}

Working Fiddle

【讨论】:

  • @AndFinally 感谢仅供参考,您可以完全用 css 显示属性值替换表格元素,例如 tabletable-columntable-rowtable-cell。如果您检查 MDN 以获得简短而清晰的信息会更好。
【解决方案2】:

这是一个 jQuery 答案,但我实际上是昨天写的,所以我知道它有效:

function setToTargetHeight(obj1, obj2){

    var targetHeight = $(obj1).innerHeight();

    $(obj2).css('height', targetHeight);

}

所以在使用中会是这样的:

setToTargetHeight('#theTextDiv','#theImageDiv');

这个名字很尴尬,所以如果有人对如何命名这个函数有任何建议,将不胜感激。

【讨论】:

  • 感谢 plushy,我认为 CSS 解决方案更适合我的特殊情况,但最好将其加入其中。
猜你喜欢
  • 2017-06-17
  • 1970-01-01
  • 2010-11-13
  • 2018-09-09
  • 2014-09-28
  • 2015-02-20
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多