Day 10 – Flexbox & Justify-Content in CSS

Day 10 – Flexbox & Justify-Content in CSS

📥 Click here to download the notes.


📌 Why Flexbox?

In web design, placing elements perfectly on a page is just as important as creating them.
That’s where Flexbox comes in — a CSS layout module that makes it easy to arrange items in rows or columns, align them properly, and create responsive layouts without complicated CSS hacks.


🧩 How to Use Flexbox

To use Flexbox, you first need to set the display property to flex on the container element.

Example:

CSS:
.container {
display: flex;
}

Once you do this, all direct child elements inside .container become flex items and can be arranged easily.


📍 Flex Direction

The flex-direction property controls whether the flex items are displayed side-by-side or top-to-bottom.

Options:

  • row → Elements are placed side-by-side (horizontally).

  • column → Elements are placed top-to-bottom (vertically).

Example:

css:
.container {
display: flex;
flex-direction: row; /* or column */
}

🎯 Justify-Content – Horizontal Alignment

The justify-content property aligns items along the horizontal axis (left to right).

Values:

  • flex-start → Items are placed at the start of the container.

  • center → Items are placed in the center horizontally.

  • flex-end → Items are placed at the end of the container.

  • space-between → First item at the start, last item at the end, space distributed between items.

  • space-around → Equal space on both sides of each item.

Example:

css:
.container {
display: flex;
justify-content: space-between;
}

📏 Align-Items – Vertical Alignment

The align-items property aligns items along the vertical axis (top to bottom).

Example:

css:
.container {
display: flex;
align-items: center; /* top, center, bottom */
}

📌 Full Example

<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
height: 300px;
background-color: #f2f2f2;
}
.box {
width: 100px;
height: 100px;
background-color: tomato;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
</body>
</html>

📝 Key Takeaways

  • Always set display: flex on the parent container to use Flexbox.

  • Use flex-direction to choose between row or column layouts.

  • Use justify-content to align items horizontally.

  • Use align-items to align items vertically.

Leave a Reply

Your email address will not be published. Required fields are marked *