Flex Layout 1
Flexbox is like LEGO blocks.
Just as you can stack LEGO blocks to create your desired shape, using Flexbox allows you to stack web page elements to create the desired layout of your web page.
In the past, to arrange content in the center, left, or right, you had to use complex CSS rules. However, with Flexbox, you can easily align elements.
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Flex Container & Flex Items
In Flexbox, the box that wraps elements is called the Flex Container
, and the elements inside the box are called Flex Items.
-
Flex Container
: The parent element to which the Flexbox layout is applied, and its child elements are called Flex Items. -
Flex Item
: Each element inside the Flex Container. These elements are aligned or arranged according to the properties of the Container.
How to use Flexbox
.container {
display: flex;
}
As shown above, adding the display: flex;
property to the CSS makes the element a Flex Container, and all child elements within it automatically become Flex Items.
Key Flexbox Properties
1. display: flex;
This property defines the Flex Container, and by applying the flex property, the child elements within the container become Flex Items.
.container {
display: flex;
}
2. flex-direction
Defines the direction in which the Flex Items are placed. Setting it to row
arranges them horizontally, while setting it to column
arranges them vertically.
.container {
flex-direction: row; /* or column */
}
3. flex-wrap
Defines whether the Flex Items in the Flex Container should be placed on a single line or wrapped onto multiple lines as needed.
Setting flex-wrap: nowrap;
places the Flex Items on a single line, while setting flex-wrap: wrap;
allows the Flex Items to wrap onto new lines if they exceed the width of the parent container.
.container {
flex-wrap: nowrap; /* places flex items on a single line */
}
Practice
Here is a simple implementation of a Flexbox layout:
<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>
.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;
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.