Search code examples
cssflexboxcentering

Flexbox - center horizontally without flex-direction: column


It is possible to get something like on the picture with flex box? I can't center right div with flex, and always get left-right in the same row, and third in second row.

enter image description here

  .table-area {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  .table-item{
    border: 1px solid red;
    background: gray;
    flex-basis: 40%;
  }
<div class="table-area">
    <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
    </div>
    <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
    </div>
    <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
    </div>
</div>


Solution

  • Here's one method: Use the transform property with the translate function.

    .table-area {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
    
    .table-item {
      border: 1px solid red;
      background: gray;
      flex-basis: 40%;
    }
    
    .table-item:nth-child(2) {
      transform: translateY(50%);
    }
    <div class="table-area">
      <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
      </div>
      <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
      </div>
      <div class="table-item">
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
        <p>Test</p>
      </div>
    </div>