skip to Main Content

I have design requirement to align a div to another div just like below figure

  • Box 1: dynamic height and width
  • Box 2 and 4: dynamic height and fixed width
  • Box 3: fix width and height
  • Box 1 and box 3 should be vertically aligned with each other

enter image description here

I already tried with css grid but it doesn’t fix to the req. Maybe anyone can have a solution for this? thanks

2

Answers


  1. Do you mean something like this?

    .row {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .col {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    
    .box {
      border: solid 1px #000;
      padding: 10px;
    }
    
    #box-2,
    #box-4 {
      width: 200px;
    }
    
    #box-3 {
      width: 200px;
      height: 100px;
    }
    <div class="row">
      <div class="col">
        <div id="box-1" class="box">1</div>
      </div>
      <div class="col">
        <div id="box-2" class="box">2</div>
        <div id="box-3" class="box">3</div>
        <div id="box-4" class="box">4</div>
      </div>
    </div>

    https://codepen.io/mickeyuk/pen/zYbzJzO

    Login or Signup to reply.
  2. Use CSS grid like below:

    .container {
      display: grid;
      gap: 5px;
      grid-template-rows: auto 80px auto; /* this contain the fixed height of 3 */
    }
    
    .container div:nth-child(1) {
      grid-row: 2; /* 1st child in second row */
      align-self: center; 
    }
    
    /* 2nd to 4th child in second column */
    .container :nth-child(n + 2) {
      grid-column: 2;
    }
    
    .container > div {
      border: 1px solid;
      padding: 5px;
    }
    <div class="container">
      <div style="height: 120px">1</div>
      <div style="height: 50px">2</div>
      <div>3</div>
      <div style="height: 150px">4</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search