获取前一个元素的高度

时间:2016-04-03 16:40:26

标签: html css

我可以仅使用CSS获得前一个元素的高度吗? 我正在使用calc()函数来设置div B的动态高度。

#b{
  height:calc(100vh - heightOfPreviousElement);
}

我需要知道前一个元素的高度。

enter image description here

我所知道的是,100vh等于屏幕高度的100%。

我在下面的答案中使用了代码。使用flex,

我有一个问题。橙色的高度变小。 enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用flexbox轻松实现所需的效果。诀窍是允许蓝色容器(具有灵活高度的容器)在需要时使用flex: 1 1 auto增大尺寸,这只是简写:

flex-grow: 1;
flex-shrink: 1;
flex-basis: auto;

请参阅下面的概念验证代码段:

body {
  padding: 0;
  margin: 0;
}
.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: no-wrap;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
.wrapper > div {
  width: 100%;
}
#c1 {
  background-color: #880015;
  color: #fff;
  height: 60px;
  margin-bottom: 10px;
}
#c2 {
  background-color: #ff7f27;
  }
#c3 {
  background-color: #00a2e8;
  flex: 1 1 auto;
  margin-bottom: 10px;
  }
<div class="wrapper">
  <div id="c1">height: 60px</div>
  <div id="c2">height: auto (determined by content?)</div>
  <div id="c3">flexible height</div>
</div>

答案 1 :(得分:0)

不,你不能在CSS中选择前一个元素。

您可能对使用.css()方法选择上一个元素和应用高度的JQuery PrevParents方法感兴趣吗?

相关问题