Languages

CSS - How to use flexbox with 3 elements per row keeping last elements position?

9 points
Asked by:
elmer
646

I would like to create grid that contains 3 elements per row. I would like to keep elements order even last row have 1 or 2 elements.

Is it possible using only CSS?

1 answer
3 points
Answered by:
elmer
646

You can use spacer elements that are not visible at the end (add columns_count - 1 spacer elements at the end).

Example solution:

// ONLINE-RUNNER:browser;

<html>
<head>
  <style>

    div.container {
        border: 1px solid red;
        display: flex;
        flex-wrap: wrap;
    }

    div.child {
        margin: 10px;
        padding: 10px;
        border: 1px solid red;
        flex: calc(33% - 42px); /* 33% - (margins + paddings + borders) */
    }
    
    div.spacer {
        margin: 0 10px;
        padding: 0 10px;
        flex: calc(33% - 40px); /* 33% - (margins + paddings) */
    }

  </style>
</head>
<body>
  <div class="container">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
    <div class="spacer"></div>
    <div class="spacer"></div>
  </div>
</body>
</html>

 

Other case:

// ONLINE-RUNNER:browser;

<html>
<head>
  <style>

    div.container {
        border: 1px solid red;
        display: flex;
        flex-wrap: wrap;
    }

    div.child {
        margin: 10px;
        padding: 10px;
        border: 1px solid red;
        flex: calc(33% - 42px); /* 33% - (margins + paddings + borders) */
    }
    
    div.spacer {
        margin: 0 10px;
        padding: 0 10px;
        flex: calc(33% - 40px); /* 33% - (margins + paddings) */
    }

  </style>
</head>
<body>
  <div class="container">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
    <div class="child">8</div>
    <div class="spacer"></div>
    <div class="spacer"></div>
  </div>
</body>
</html>

 

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join