3

I have a few "div" 's inside a "nav":

<nav>
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</nav>

I want to align div A,B,C,D at the top, but div E and F at the bottom:

This code works for the last item (F), but E floats exactly in the middle:

nav {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
  
        & > div:nth-child(5),
        & > div:nth-child(6) {
          margin-top: auto;
        }
}

enter image description here

How can I make div E stick with div F at the bottom (without extra wrapping div's inside the nav)?

enter image description here

JSFiddle

Always Helping
  • 14,316
  • 4
  • 13
  • 29
Wolf359
  • 2,620
  • 4
  • 42
  • 62

1 Answers1

4

You can do this two ways below.

Using nth-child()

Use margin-top:auto on nth-child(5) only to get your desired results

Live demo:

nav {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: 250px;
  width: 150px;
  border: 1px solid red;
}

div {
  display: flex;
  justify-content: center;
  border: 1px solid blue;
  width: 100%;
}

div:nth-child(5) {
  margin-top: auto;
}
<nav>
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</nav>

Using :nth-last-child()

You can also use nth-last-child() to achieve this.

nav {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: 250px;
  width: 150px;
  border: 1px solid red;
}

div {
  display: flex;
  justify-content: center;
  border: 1px solid blue;
  width: 100%;
}

div:nth-last-child(2) {
  margin-top: auto;
}
<nav>
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</nav>
Always Helping
  • 14,316
  • 4
  • 13
  • 29