1

Can i get the height of the previous element using only CSS? I am using calc() function to set dynamically height of the div B.

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

I need to know the height of the previous element.

enter image description here

what i know is that, 100vh is equal to 100% of the screen height.

I used the code in the answer below.Using flex,

I have one problem. The height of the color orange become smaller. enter image description here

JMA
  • 974
  • 3
  • 13
  • 41
  • It sounds like an XY problem to me. Perhaps the layout can be made using other methods such as flexbox, since you're simply adjusting the height based on another element's (a sibling). Unfortunately CSS doesn't allow selecting previous elements or parents (hence the name **cascading**). Update your question to include more details, such as what kind of layout do you want to achieve visually, and snippets of your code—that'll be extremely helpful. – Terry Apr 03 '16 at 16:44
  • possible duplicate: http://stackoverflow.com/q/33129660/3597276 – Michael Benjamin Apr 03 '16 at 17:06

2 Answers2

2

You can easily achieve the effect you're looking for using flexbox. The trick is to allow the blue container (the one with the flexible height) to grow in size whenever the need arises, using flex: 1 1 auto, which is simply a shorthand for:

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

See proof-of-concept code snippet below:

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>
Terry
  • 63,248
  • 15
  • 96
  • 118
  • I used this code but have a problem. See my updated question. – JMA Apr 04 '16 at 03:05
  • @JohnArellano That's because you don't have sufficient height to contain all of them. When this happens, the flex element collapses in dimension. You can prevent this by setting `flex-shrink: 0` (it is `1` by default). – Terry Apr 04 '16 at 09:23
0

No you can't select a previous element in CSS.

You might be interested in JQuery Prev OR Parents method for selecting previous element and apply height using .css() method?

Faisal Ashfaq
  • 2,545
  • 4
  • 28
  • 41