首页 > 解决方案 > 如何使元素高度相同

问题描述

我举了一个例子来代表我当前的问题。

我想要这个结构。我在蓝色部分尝试了 height: 100% 但它没有用,所以我给了 height: 80vh。

这是一个问题,因为如果您使窗口变小或变大(不响应),则不再对齐并且会变得更糟。

如何使内容的左侧和右侧在顶部和底部对齐,边缘顶部为 5px 到黑色部分?

.red {
  background: red;
}

.blue {
  background: blue;
  height: 80vh;
}

.green {
  background: green;
}

img {
  width: 100%;
  height: 100%;
}

.black {
  background: black;
  margin-top: 5px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <div class="row">
        <div class="col-xs-12">
          <div class="red">
            <img src="https://www.w3schools.com/w3images/fjords.jpg" />
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <div class="green">
            <img src="https://www.w3schools.com/w3images/fjords.jpg" />
          </div>
        </div>
      </div>
    </div>
    <div class="col-xs-6">
      <div class="blue">

      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12">
      <div class="black">
        Hi
      </div>
    </div>
  </div>
</div>

标签: htmlcss

解决方案


我解决了与此类似的问题,并为它创建了一个您可能想尝试的 jQuery 解决方案,它对我来说效果很好。

基本上,该函数获取您知道将是最高的列的高度。如果该内容大于其他内容,则将其他内容的高度设置为与较高内容相同。

$(document).ready(function () {
   var tallest = $(".red").height();
   var shortcolumn1 = $(".blue").height();       
   if (tallest >= shortcolumn1) {    
       $(".blue").css("height",""+ tallest +"px");
       $(".green").css("height",""+ tallest +"px");
    }
   else {       
   }
 });

推荐阅读