skip to Main Content

Is it possible to get this grid with flexbox or css grid without changing the HTML?

enter image description here

<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
 </div>

I know it can be done with wrapping flex or grid containers, but I am really looking to not change the HTML at all. Also the number of items might be more so need a way to do it without knowing the number of items.

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution, but it requires a high number on grid-row like 9999 and you can't use gap as it will cause a lot of space with the high number.

    .wrapper {
        display: grid;
        grid-template-columns: 1fr 3fr;
    }
    .wrapper > div {
        background-color: #ddd;
        grid-column: 1;
        margin: .1em;
        padding: 1em;
    }
    .b {
        grid-column: 2;
        grid-row: 1 / 9999;
    }
    <div class="wrapper">
      <div class="a">A</div>
      <div class="b">B</div>
      <div class="c">C</div>
      <div class="d">D</div>
      <div class="e">E</div>
    </div>


  2. Answering your question – yes, it is possible.
    If the number of elements is known:

    .container {
      display: grid;
      grid-template: repeat(4, 40px) / 40px 1fr;
      grid-gap: 8px;
    }
    
    .container div {
      border:solid 1px blue;
    }
    
    .container div:nth-child(2) {
      grid-row: span 4;
    }
    <div class="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
    </div>

    If the number of elements is unknown:

    * {
      box-sizing: border-box;
    }
    
    .container {
      --size: 40px;
      --gap: 8px;
      display: grid;
      grid-auto-rows: var(--size);
      gap: var(--gap);
      position: relative;
    }
    
    .container div {
      border: solid 1px blue;
      width: var(--size);
    }
    
    .container div:nth-child(2) {
      position: absolute;
      inset: 0 0 0 calc(var(--size) + var(--gap));
      width: unset;
    }
    <div class="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search