Centering element in grid container

52 Views Asked by At

I want to align some elements at the very center of my container which has a display grid. At the exact center of that element though there is the grid gap.

So I want to align my elements, the two buttons with the arrow, at the very center (where there is the 7).

I know that it works fine with a positions absolute but I really want to avoid it because I'm using svelte with transitions and using position absolute changes the elements position.

Here is a image of my page and grid layout:

Page layout

And here's the code for it:

.content-container {
    display: -ms-grid;
    display: grid;
    min-height: 0;
    min-width: 0;
    grid-auto-flow: dense;
    min-height: 100vh;
    min-width: 100vw;

    grid-template-columns: repeat(12, minmax(0, 1fr));
    gap: 50px;

    //adding the padding to the container
    padding: 50px;
    
    background: blue;
}
.nav-link {
    align-self: start;
    justify-self: center;
}
.nav-link.work {
    align-self: end;
}
<section class="content-container">
    <div class="nav-link about">
        btn
    </div>
    <div class="nav-link work">
        btn
    </div>
</section>

1

There are 1 best solutions below

3
SyndRain On BEST ANSWER

One way is to have the two buttons to span between column 6 and 7 (grid-column: 6 / span 2). You can guarantee them to be at the top and bottom row by specifying grid-row:1 and grid-row:span 1.

.content-container {
  display: -ms-grid;
  display: grid;
  min-height: 0;
  min-width: 0;
  grid-auto-flow: dense;
  min-height: 100vh;
  min-width: 100vw;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 50px;
  padding: 50px;
  outline: 1px solid red;
}

.nav-link {
  grid-column: 6 / span 2;
  align-self: start;
  justify-self: center;
}

.nav-link.about {
  grid-row: 1;
}

.nav-link.work {
  grid-row: span 1;
  align-self: end;
}
<section class="content-container">
  <div class="nav-link about">
    btn
  </div>
  <div class="nav-link work">
    btn
  </div>
</section>