CSS

Align Individual Flexbox Items with `align-self`

Learn to override default flex container alignment and position specific flex items using `align-self` for precise vertical or horizontal placement within a flex container.

.flex-container {
  display: flex;
  height: 200px;
  border: 2px solid #333;
  align-items: flex-start; /* Default alignment for all items */
  justify-content: space-around;
}

.flex-item {
  width: 80px;
  padding: 10px;
  background-color: #66b3ff;
  color: white;
  text-align: center;
  margin: 5px;
}

.flex-item:nth-child(2) {
  align-self: center; /* Override default for second item */
  background-color: #ff9933;
}

.flex-item:nth-child(3) {
  align-self: flex-end; /* Override default for third item */
  background-color: #33cc66;
}

.flex-item:nth-child(4) {
  margin-top: auto; /* Push item to the bottom in a column direction, or right in row */
  margin-bottom: auto; /* Center with respect to available space */
  background-color: #cc66ff;
}

/* HTML Structure */
/*
<div class="flex-container">
  <div class="flex-item">Item 1 (Start)</div>
  <div class="flex-item">Item 2 (Center)</div>
  <div class="flex-item">Item 3 (End)</div>
  <div class="flex-item">Item 4 (Auto Margins)</div>
</div>
*/
How it works: This snippet demonstrates how to control the alignment of individual items within a flex container using `align-self`. While `align-items` sets the default cross-axis alignment for all flex items, `align-self` can be applied to specific items to override this default. `align-self: center`, `flex-start`, and `flex-end` are common values. Additionally, using `margin: auto` on a flex item can be a powerful way to push an item to one side or center it, consuming all available space in that direction.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs