父级Div如何保持最高子元素的高度

3

我一直在谷歌上搜索潜在的解决方案,但至今未找到符合要求的。

<div class="parent">
    <div class="child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="child2">I'm 80px tall and hidden until needed</div>
    <div class="child3">I'm 100px tall and hidden until needed</div>
</div>
  • 我需要一个父Div和一些子Div。
  • 在任何时候只有一个子Div是可见的。
  • 父Div必须始终与最高的子Div保持相同的高度,且不会扩展或收缩。

我将使用jQuery来更改可见子Div的CSS,但如果可能的话,我更喜欢使用CSS解决高度问题。

无需支持IE8/9/10。

有人有想法吗?


2
你想要的在 jQuery 中非常容易实现,但是我对使用 CSS 有一些疑虑。 - Rana Ghosh
尝试为父级 div 添加 display:flex 属性(如果子元素是列排列)。但如果子元素一个接一个地堆叠,则需要使用 jQuery 解决方案。 - patelarpan
2个回答

3
我希望这是您想要的:
  1. 使用 flex 显示使子元素按列显示。
  2. 将它们的 opacity 设置为0,以便子元素仍然保留在父div中,这将设置父元素高度与最高的子元素相同。
  3. 创建一个新类 visible 来样式化可见的子元素,并将默认隐藏的子元素的 width: 0px,而可见的子元素将有 width: 100%

function show(element) {
  $('.parent div').removeClass('visible');
  $('.' + element).addClass('visible');
}
.parent {
  border: 1px dashed #000;
  display: flex;
}

.child1 {
  height: 60px;
  background: red;
}

.child2 {
  height: 80px;
  background: yellow;
}

.child3 {
  height: 100px;
  background: orange;
}

.parent div {
  opacity: 0;
  width: 0px;
}

.parent div.visible {
  opacity: 1;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child1 visible">I'm 60px tall and visible; my parent is 100px tall</div>
  <div class="child2">I'm 80px tall and hidden until needed</div>
  <div class="child3">I'm 100px tall and hidden until needed</div>
</div>

<br/>
<button onclick="show('child1')">Child 1</button>
<button onclick="show('child2')">Child 2</button>
<button onclick="show('child3')">Child 3</button>


1

使用 opacity 属性将元素隐藏,值为 01,并且父元素应该与最高的子元素一样高。

请参见以下代码片段:

$(function(){ 
  $(".c").fadeTo(0,0);
  $(".child1").fadeTo(0,1).addClass("visible");
  $(".btn").click(function(){
    $(".c").fadeTo(0,0);
    $(".visible").removeClass("visible").next().fadeTo(0,1).addClass("visible");
  });

});
.parent { position:relative; border:2px solid red; display:flex  }
.c { border:2px solid blue; }
.child1 { height:60px; }
.child2 { height:80px; }
.child3 { height:100px; }
<div class="parent">
    <div class="c child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="c child2">I'm 80px tall and hidden until needed</div>
    <div class="c child3">I'm 100px tall and hidden until needed</div>
</div>

<button class="btn">Show Next Child</button>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接