2

For example, I'd like to use a class which has at the most 3 columns, but If I had just 2 elements, this row gonna align this elements to the center Is it possible with CSS grid?

in the example below, I'd like to center the elements of second line

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>grid</title>
    <style>
        .grid {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-gap: 10px;
        }

        .grid > div {
        height: 100px;
        width: 100px;
        background-color: red;
        }
    </style>
</head>
<body>
    <div class="grid">
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
    </div>
</body>
</html>

DEMO

Henrique
  • 362
  • 1
  • 5
  • 13

2 Answers2

0

Using JavaScript, you can check if the row only has two elements, then:

  1. Move the second element to the third column
  2. Delete the middle column

This way that row will only have 2 columns, and will be aligned to center.

0

I think I did the result that I was looking for with flexbox

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>grid</title>
    <style>
        .grid {
            display: flex;
            flex-wrap:wrap;
        }

        .grid > div {
            background: red;
            height: 100px;
            margin: 10px;
            flex-grow: 1;    
           width: calc(100% * (1/3) - 10px - 10px);
        }
    </style>
</head>
<body>
    <div class="grid">
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
        <div class="block"></div>
    </div>
</body>
</html>

DEMO

Henrique
  • 362
  • 1
  • 5
  • 13