Home > Software engineering >  How to center CSS Grid but child elements at the start?
How to center CSS Grid but child elements at the start?

Time:08-15

I want to implement this layout with CSS Grid or Flexbox. If necessary, it is also possible to use JS.

enter image description here

In the pictures you can see how the child elements should be arranged when adding 1, 2, 3 and 4 child elements in a sequence

The content is generated dynamically. TThat is, the number of child elements is unknown. There may be a maximum of 3 child elements in a row. The grid items should be centered. The whole Layout should also be responsive.

.parent {
  background-color: red;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
  justify-content: center;
  /* 3* 350px width of child elements   2*20px gap*/
  max-width: 1090px; 
  padding: 20px;
}

.child {
  width: 350px;
  height: 450px;
  background-color: blue;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

It is currently not responsive (if possible without media queries) and the child elements are not centered.

Do you know how I can implement this layout?

CodePudding user response:

Don't define 3 columns but rely on implicit column creation:

.parent {
  background-color: red;
  display: grid;
  grid-auto-columns: calc((100% - 2*20px)/3); /* size of one column */
  grid-gap: 20px;
  justify-content: center;
  margin: 10px;
}

.child {
  height: 50px;
  background-color: blue;
}

/* place each item in the adequate column */
.child:nth-child(3n   1) {grid-column: 1}
.child:nth-child(3n   2) {grid-column: 2}
.child:nth-child(3n   3) {grid-column: 3}
<div >
  <div ></div>
</div>
<div >
  <div ></div>
  <div ></div>
</div>
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

I think I have something for this using implicit grids:

* {
  box-sizing: border-box;
}

body {
  display: flex;
  flex-direction: column;
  gap: 50px;
  background: #000;
}

section {
  width: 100%;
  padding: 30px;
  background: #666;
}

.grid-inner {
  display: grid;
  gap: 30px;
  justify-content: center;
  grid-auto-columns: calc(33% - 15px);
}

.box {
  padding: 30px;
  background: white;
  border: 1px solid black;
}

.box:nth-child(2) {
  grid-column: 2;
}

.box:nth-child(3) {
  grid-column: 3;
}
<section>
  <div >
    <div ></div>
  </div>
</section>

<section>
  <div >
    <div ></div>
    <div ></div>
  </div>
</section>

<section>
  <div >
    <div ></div>
    <div ></div>
    <div ></div>
  </div>
</section>

<section>
  <div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
  </div>
</section>

<section>
  <div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
  </div>
</section>

  • Related