首页 > 解决方案 > 通过 CSS 根据另一个 div 调整 div 的高度

问题描述

我有两个 DIV(一个是侧边栏,另一个是内容部分),我需要具有相同的高度,但我有一个问题。侧边栏包括一些lis。我希望侧边栏的高度与内容部分相同,但是当我使用 时flex,侧边栏的高度可以比内容部分长(因为两个部分都是动态的)。所以当高度长于内容部分时,我需要滚动侧边栏

<section class="container">
    <div class="sidebar">
        <ul>
            <li><li>
            <li><li>
            <li><li>
            <li><li>
            <li><li>
        </ul>
    </div>
    <div class="content"></div>
</section>

我的 CSS 代码:

.container {
    display: flex;
}
.sidebar,.content {
    flex: 1 0 auto;
}

我什至使用了 JQuery,但我们看到了错误的高度,因为图像在内容部分加载缓慢。

我的 jQuery 代码:

jQuery(document).ready(function($) {

    $(".sidebar").height($(".content").height());

});

我什至使用了以下代码,但没有任何反应:

jQuery( window ).load(function($) {

    $(".sidebar").height($(".content").height());

});

我不想使用position:absolute,因为...您可以在此链接中看到我的页面:https ://end-eng.com/landing-grammar/

标签: jquerycss

解决方案


你所拥有的非常接近!如果您改为在父级上设置 flex 属性,您将拥有两个等高的 div。我添加了一些颜色来说明:

.container {
    display: flex;
    flex: 1 0 auto;
}
.sidebar {
    background: red;
}

.content {
  background: lime;
}
<section class="container">
    <div class="sidebar">
        <ul>
            <li><li>
            <li><li>
            <li><li>
            <li><li>
            <li><li>
        </ul>
    </div>
    <div class="content">hello content</div>
</section>

flex以下是您正在使用的速记的一些读物: https ://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow

如果您需要在高度长于内容时滚动侧边栏,那么您可以使用 jQuery 来匹配resize事件中元素的高度(以保持一致),如下所示:

$(document).ready(function() {
  var a = '.content';
  var b = '.sidebar'
  matchHeight(a, b); // set at beginning
  $(window).resize(function() {
    matchHeight(a, b); // reset on window resize
  })
});

// set height of one element to another
// target: height to match
// el: element to match to target height
function matchHeight(target, el) {
  var targetHeight = $(target).height();
  $(el).css('height', targetHeight);
}
.container {
  display: flex;
  flex: 1 0 auto;
}

.sidebar {
  background: red;
  overflow-y: scroll;
  min-width: 50px;
}

.sub-container {
  background: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<section class="container">
  <div class="sidebar">
    <ul>
      <li>
        <li>
          <li>
            <li>
              <li>
                <li>
                  <li>
                    <li>
                      <li>
                        <li>
    </ul>
  </div>
  <div class="sub-container">
    <div class="content">
      Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
      one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.
    </div>
  </div>
</section>


推荐阅读