Search code examples
twitter-bootstrapcssbootstrap-4twitter-bootstrap-4

Equal height of columns in Bootstrap 4


I have a little non-conventional DIV in this design as shown below. I could use a height and do it but I want it to change dynamically: enter image description here For instance, if the DIV has more content and the height changes in one of the block on the right, the left DIV auto adjust it's height as well. I wonder if flex could help. Here's how it should change to: enter image description here

I have this HTML so far:

<div class="container">
  <div class="row row-eq-height">
      <div class="col-sm-8 col-8">
        <div class="black">
          <p>Bar Graph or Line Graph</p>
        </div>
      </div>
      <div class="col-sm-4 col-4">
        <div class="red">
          <p>numbers</p>
        </div>
        <div class="purple">
          <p>numbers</p>
        </div>
        <div class="green">
          <p>numbers</p>
        </div>
        <div class="blue">
          <p>numbers</p>
        </div>
      </div>
  </div>
</div>

and CSS:

p { color: #fff; }
.black { background-color: black; }
.green { background-color: green; }
.red { background-color: red; }
.blue { background-color: blue; }
.purple { background-color: purple; }

JSFiddle Demo


Solution

  • You can use flexbox for this.

    Update

    And another way:

    https://jsfiddle.net/persianturtle/ar0m0p3a/5/

    .row-eq-height > [class^=col] {
      display: flex;
      flex-direction: column;
    }
    
    .row-eq-height > [class^=col]:last-of-type div {
      margin: 10px;
    }
    
    .row-eq-height > [class^=col]:last-of-type div:first-of-type {
      margin-top: 0;
    }
    
    .row-eq-height > [class^=col]:last-of-type div:last-of-type {
      margin-bottom: 0;
    }
    
    .row-eq-height > [class^=col]:first-of-type .black {
      flex-grow: 1;
    }
    

    Update

    A better way with more specific classes:

    https://jsfiddle.net/persianturtle/ar0m0p3a/3/

    .row-eq-height > [class^=col]:first-of-type {
      display: flex;
    }
    
    .row-eq-height > [class^=col]:first-of-type .black {
      flex-grow: 1;
    }
    
    .blue p {
      margin: 0;
    }
    

    Original way:

    https://jsfiddle.net/persianturtle/ar0m0p3a/1/

    [class^=col] {
      display: flex;
      flex-direction: column;
    }
    
    [class^=col] div {
      flex-grow: 1
    }