Flexbox Container Properties: Justify-Content & Align-Items

So, you've met Flexbox, but now you need to control how items align and distribute within a container? Enter Justify-Content and Align-Items—the dynamic duo that makes Flexbox flexible!

With these two properties, you can say goodbye to complicated positioning hacks and effortlessly arrange elements like a CSS ninja!

In this guide, we’ll cover: 

  • What justify-content and align-items do.
  • The different alignment options available.
  • Real-world examples to make your layouts pop!

Ready? Let’s dive in!

Justify-Content: Controlling Horizontal Alignment

The justify-content property is used to align flex items horizontally along the main axis (left to right for row, top to bottom for column).

Syntax:

.container {
  display: flex;
  justify-content: center;
}

Available Options:

Value Description
flex-start (default) Aligns items to the start of the flex container.
flex-end Pushes items to the end of the container.
center Centers items perfectly.
space-between Spreads items evenly, with space between them.
space-around Gives equal space around each item.
space-evenly Distributes items with equal spacing everywhere.

Example:

.container {
  display: flex;
  justify-content: space-between;
}
<div class="container">
  <div class="box">Item 1</div>
  <div class="box">Item 2</div>
  <div class="box">Item 3</div>
</div>

Boom! Items are now evenly spaced!

Align-Items: Controlling Vertical Alignment

While justify-content handles horizontal alignment, align-items aligns items vertically along the cross axis.

Syntax:

.container {
  display: flex;
  align-items: center;
}

Available Options:

Value Description
stretch (default) Stretches items to fill the container.
flex-start Aligns items to the top of the container.
flex-end Aligns items to the bottom of the container.
center Centers items vertically.
baseline Aligns items by their text baseline.

Example:

.container {
  display: flex;
  align-items: flex-end;
}
<div class="container">
  <div class="box">Item 1</div>
  <div class="box">Item 2</div>
  <div class="box">Item 3</div>
</div>

Now all items are stuck to the bottom!

Justify-Content + Align-Items = Perfect Centering!

Want perfectly centered elements? Use both properties together!

Example:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full-screen height */
}
<div class="container">
  <div class="box">Centered!</div>
</div>

Bam! Everything is now dead center!

Conclusion: Flexbox Alignment Like a Boss!

Justify-Content = Controls horizontal alignment.
Align-Items = Controls vertical alignment.
Use both together for perfect centering!

Now go forth and align your elements like a pro!

Post a Comment

0 Comments