0

I am trying to center content using grid and inline-flex. I'm able to do it if I use flex-box and flex-direction: column;, but I'm really hoping to find a minimal code version using grid instead.

Here is the layout I'm looking for, which relies on flex-direction: column; on the .grid. Please run the code snippet below to see the layout.

.parent-grid {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
}

.grid {
  grid-column-start: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  margin-bottom: 25px;
}

.btn {
  border: 1px solid black;
  display: inline-flex;
  padding-left: 45px;
  padding-right: 45px;
  height: 38px;
  align-items: center;
}

.btn-text {
  margin-right: 20px;
}

.img {
  height: 30px;
  width: 30px;
  background-color: red;
}
<div class="parent-grid">
  <div class="grid">
    <h1>
      My Long Title Goes Here
    </h1>

    <a class="btn">
      <span class="btn-text">
        My btn text
      </span>
      <div class="img"></div>
    </a>
  </div>
</div>

Here's my attempt using grid. I'm not sure why the button expands to full width. It's using inline-flex, so shouldn't that mean its width is auto, rather than 100%?

.parent-grid {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
}

.grid {
  grid-column-start: 2;
  display: grid;
  align-items: center;
}

h1 {
  margin-bottom: 25px;
}

.btn {
  border: 1px solid black;
  display: inline-flex;
  padding-left: 45px;
  padding-right: 45px;
  height: 38px;
  align-items: center;
}

.btn-text {
  margin-right: 20px;
}

.img {
  height: 30px;
  width: 30px;
  background-color: red;
}
<div class="parent-grid">
  <div class="grid">
    <h1>
      My Long Title Goes Here
    </h1>

    <a class="btn">
      <span class="btn-text">
        My btn text
      </span>
      <div class="img"></div>
    </a>
  </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Jordan Carter
  • 1,276
  • 3
  • 19
  • 43
  • add margin: auto; to the button – Temani Afif Jun 01 '20 at 19:21
  • @TemaniAfif Thanks, that worked. Feel free to write it as an answer and I'll accept it. It's just odd how it didn't automatically align it since inline-flex was used, like Flexbox does. Note that adding auto margins also works when it's displayed as flex, rather than inline-flex; – Jordan Carter Jun 02 '20 at 19:05
  • @TemaniAfif I used margin-left: auto; margin-right: auto; just to keep things clear. Note that margin: auto would also add auto margins to the top and bottom. Margin: 0 auto; would also keep things brief and prevent this. – Jordan Carter Jun 02 '20 at 19:06

0 Answers0