悬浮元素100%高度动态包装



我在一个包装器中有两列。一根柱子比另一根高。我希望较短的列的高度为100%,以便与较高的列匹配。所有高度都是动态的,因此不能以像素为单位进行定义。

演示https://jsfiddle.net/L0Lqe4ny/

<div class="wrapper">
    <div class="col1"> short column // not much content </div>
    <div class="col2"> tall columns // lots of content </div>
</div>

您将在示例中看到红色列比蓝色列高。如何将蓝色列设置为包装器的100%高度。

我知道我可以通过定义高度来轻松做到这一点,这不是一个选项。如果我使用表格进行布局,我也可以这样做,但我不想这样做。我也可以通过使用javascript从高列中获取高度,然后设置较小列的高度来实现这一点。不过我想要一个只使用CSS的方法。谢谢

只需一点jQuery,就可以实现这一点,看看https://jsfiddle.net/20d2an0n/

$(document).ready(function(){
    var blue_height = $('.col1').height();
    var red_height = $('.col2').height();
    if(blue_height < red_height)
        $('.col1').height(red_height);
    else
        $('.col2').height(blue_height);
});

你的小提琴被修改了:https://jsfiddle.net/ybywo28c/

使用flexbox:的纯CSS解决方案

.wrapper {
    display: flex;
    width: 300px;
}
.col1, .col2 {
    align-self: stretch;
    float: left;
    width: 140px;
    background: red;
}
.col1 {
    background: blue;
}

顺便说一句,如果从列中删除width属性并添加flex: 1;,它将在列之间均匀分布包装器的宽度;)
IE 10需要-ms前缀,不幸的是,IE8和9根本不支持它,在较旧的浏览器中,语法可能会有所不同——有些浏览器(例如Android 4.1和4.3)使用所谓的"旧语法",如果你好奇,请查看这些页面

  • https://css-tricks.com/snippets/css/a-guide-to-flexbox/

  • http://caniuse.com/#search=flex

  • https://css-tricks.com/using-flexbox/

这是你能得到的最的跨浏览器解决方案,我从css-tricks.com:复制粘贴了它

.wrapper {
  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
  width: 300px;
}
.col1, .col2 {
  float: left;
  width: 140px;
  background: red;
}
.col1 {
    background: blue;
}

最新更新