Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put a flex item to the end? [duplicate]

Tags:

html

css

flexbox

I want the flex items in the center and only the last item at the end, but when I use margin-left: auto, the other items are put in the beginning.

#container {
  background-color: wheat;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item {
  background-color: thistle;
  margin: 5px;
  padding: 10px;
}

.item:last-child {
  margin-left: auto;
}
<div id="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>  
</div>

1 Answers

You were correct in using margin-left: auto on the last flex item. That is one way to position the last item at the end of the main axis. To keep the other flex items positioned in the center, you can simply give the first flex item .item:first-child an auto left margin. Now the items 1,2,3,4 are centered in the nav bar with number 5 (the last item) positioned at the end of the row.

#container {
  background-color: wheat;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item {
  background-color: thistle;
  margin: 5px;
  padding: 10px;
}

.item:first-child,
.item:last-child {
  margin-left: auto;
}
<div id="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>  
</div>
like image 161
Tanner Dolby Avatar answered Sep 17 '25 05:09

Tanner Dolby