Lecture

Flexbox - Basics

Flexbox is like building blocks.

Just as you can stack Lego blocks to create desired shapes, you can use Flexbox to stack elements on a web page to create the desired layout.

Previously, aligning content vertically, horizontally, or centrally required complex CSS rules, but with Flexbox, you can easily align elements.

CSS
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }

Flex Containers & Flex Items

In Flexbox, the box that wraps around elements is called the Flex Container, and the elements within this box are called Flex Items.

  • Flex Container: The parent element to which the Flexbox layout is applied, containing child elements referred to as Flex Items.

  • Flex Item: Each element inside the Flex Container that is aligned and arranged according to the container's properties.


How to Use Flexbox

CSS
.container { display: flex; }

By adding the display: flex; property in CSS as shown above, the element becomes a Flex Container, and all its child elements automatically become Flex Items.


Key Properties of Flexbox

  1. display: flex;

This property defines a Flex Container, and once the flex property is applied, the container's child elements become Flex Items.

CSS
.container { display: flex; }

  1. flex-direction

This property defines the direction in which Flex Items are placed. Setting it to row aligns the items horizontally, while setting it to column aligns them vertically.

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

  1. flex-wrap

This property defines whether Flex Items should be placed in a single line or wrapped onto multiple lines if necessary.

Setting it to flex-wrap: nowrap; forces the items to be in a single line, while setting it to flex-wrap: wrap; allows items to wrap to the next line when they exceed the container's width.

CSS
.container { flex-wrap: nowrap; /* all flex items in a single line */ }

Practice

Here's a simple code example of a Flexbox layout:

HTML
<div class="flex-container"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> <div class="box">4</div> </div>
CSS
.flex-container { display: flex; gap: 20px; padding: 20px; background-color: #ffffff; border-radius: 10px; box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.1); } .box { padding: 30px; font-weight: bold; font-size: 20px; text-align: center; background-color: #c8e6c9; border-radius: 5px; }

Follow the emphasized parts of the code to replicate it.

Mission
0 / 1

All child elements within a flex container automatically become flex items.

True
False

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help