我有两个DIV(一个是侧边栏,另一个是内容部分),我需要具有相同的高度,但是我遇到了问题。侧边栏包含一些li。我希望边栏的高度与内容部分的高度相同,但是当我使用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/

最佳答案

您所拥有的非常接近!如果改为在父对象上设置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>

07-26 00:33
查看更多