Set div height as a percentage of div

I have three div divs per line:

Right div: a div whose height is determined by its text content.

Center div: the div that should match the height of the right div.

Left div: the div I want to set to 50% of the height of the right div.

Demo

trying CSS using flexbox with left div doesn't work:

.container {
    display: flex;
}
.left {
    width: 50px;
    height: 50%;
    background-color: lightcyan;
}
.center {
    width: 50px;
    background-color: lightcoral;
}
.right {
    width: 300px;
    background-color: palegreen;
}

      

The only way I've found to let the left div calculate the percentage of the right height is to use position: absolute

like in this answer .

Absolute positioning is less than ideal because it prevents me from using the normal layout flow to position three divs next to each other in a row.

Is it possible to set the left div to a percentage of the right height, without having to use a fixed horizontal layout to position three divs per line?

The layout should only work in recent Chrome, so browser incompatibility is not an issue. I am open to solutions using flexbox or table.

+3


source to share


1 answer


I don't know what restrictions you have in your HTML structure. But a simple way to do what you need is to set the div to left

be equal to the height of the table-cell

div, and inside it is an inner div with height 50%

. This will not affect the flow of items:

Updated JsFiddle



.container {
    display: table;
}

.left {
    display: table-cell;
    position: relative;
    width: 50px;
}

.left > div {
    background-color: lightcyan;
    height: 50%;
    width: 100%;
    position: absolute;
}

.center {
    display: table-cell;
    width: 50px;
    background-color: lightcoral;
}
.right {
    display: table-cell;
    width: 300px;
    background-color: palegreen;
}
      

<div class="container">
    <div class="left">
        <div></div>
    </div>
    <div class="center"></div>
    <div class="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum porttitor vitae ante quis suscipit.
    </div>
</div>
      

Run code


+2


source







All Articles