All items centered along the vertical axis except the last which should sit on the bottom using CSS Grid?
Asked Answered
B

1

1

I'm trying to get the answer to another question to work on the vertical axis using 'Method 5 CSS Grid Layout'.

The aim is to get all items centered along the vertical axis except the last which should sit on the bottom using CSS Grid?

The requirements are:

  • The number of centered items can vary.
  • The height of the container can vary.
  • Can't change the HTML.

As you can see my first attempt at translating from the horizontal to the vertical is not working:

  • Why are the items out of order?
  • Why isn't the last item sitting on the bottom?
  • How do I fix this?

ul {
  display: grid;
  grid-template-columns: 1fr repeat(3, auto) 1fr;
  grid-column-gap: 5px;
  justify-items: center;
}

ul li:nth-child(1) {
  grid-column-start: 2;
}

ul li:nth-child(4) {
  margin-left: auto;
}

ul,
ol {
  padding: 0;
  margin: 0;
  list-style: none;
  background: pink;
}

li {
  padding: 5px;
  background: #aaa;
}

p {
  text-align: center;
}


/* My attempt to get this working on a vertical layout */

ol {
  height: 400px;
  display: grid;
  grid-template-rows: 1fr repeat(3, auto) 1fr;
  row-gap: 5px;
  justify-items: center;
}

ol li:nth-child(1) {
  grid-row-start: 2;
  background-color: coral;
}

ol li:nth-child(4) {
  margin-top: auto;
  background-color: chartreuse;
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>
<p><span>| true center |</span></p>

<ol>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ol>
Babbage answered 30/5, 2022 at 22:35 Comment(2)
in your second example, what item you want it at the bottom?Illfounded
Item 4, thanks TemaniBabbage
I
2

You are almost good, you need to add grid-auto-flow: column. You have to change the flow algorithm if you want to do the same in the opposite axis.

ul {
  display: grid;
  grid-template-columns: 1fr repeat(3, auto) 1fr;
  grid-column-gap: 5px;
  justify-items: center;
}

ul li:nth-child(1) {
  grid-column-start: 2;
}

ul li:nth-child(4) {
  margin-left: auto;
}

ul,
ol {
  padding: 0;
  margin: 0;
  list-style: none;
  background: pink;
}

li {
  padding: 5px;
  background: #aaa;
}

p {
  text-align: center;
}


/* My attempt to get this working on a vertical layout */

ol {
  height: 400px;
  display: grid;
  grid-template-rows: 1fr repeat(3, auto) 1fr;
  grid-auto-flow: column;
  row-gap: 5px;
  justify-items: center;
}

ol li:nth-child(1) {
  grid-row-start: 2;
  background-color: coral;
}

ol li:nth-child(4) {
  margin-top: auto;
  background-color: chartreuse;
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>
<p><span>| true center |</span></p>

<ol>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ol>
Illfounded answered 31/5, 2022 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.