Flexbox in CSS
Flexbox in CSS
Flexbox in CSS is the modern way to present a 1-dimensional layout. The main idea behind flexbox is to divide empty space inside a container by its child element. Flexbox makes it easy to align items inside a container in both directions horizontally and vertically. Before CSS it was quite hard to build a 1-dimensional layout with float. Flexbox is used on a container by setting its display property to flex and then its all child element would be inline elements and display as side by side
<div class="container">
<div class="box box--1"></div>
<div class="box box--2"></div>
<div class="box box--3"></div>
<div class="box box--4"></div>
</div>
.container {
display: flex;
}
.box {
width: 200px;
height: 200px;
}
.box--1 {
background-color: #000;
}
.box--2 {
background-color: #ccc;
}
.box--3 {
background-color: #c4c;
}
.box--4 {
background-color: #c8c;
}
The output will be like this
as elements are side by side now.
Flex-Direction
The default direction in flexbox is row but we can set it to a column.
.container {
display: flex;
flex-direction: column;
}
The output will be
We could also set the flex-direction to column-reverse or row-reverse.
Justify content in Flexbox
if our flex-container is inside a container having specific width then we can set our flex-container to center, left and right in its parent container. start is the default property in justify-content we can set it to center and end.
.parent-container {
width: 800px;
height: 400px;
background-color: #999;
}
.container {
display: flex;
justify-content: center;
}
output will be
.parent-container {
width: 800px;
height: 400px;
background-color: #999;
}
.container {
display: flex;
justify-content: end;
}
Align-items in CSS
As justify-content for horizontal alignment, we have also vertical alignment in flexbox using the align-items property but its parent container should have some height. The default property of align-items is stretch but we can set it to end and center.
.parent-container {
width: 800px;
height: 500px;
background-color: #999;
}
.container {
height: 500px;
display: flex;
align-items: center;
}
.parent-container {
width: 800px;
height: 500px;
background-color: #999;
}
.container {
height: 500px;
display: flex;
align-items: end;
}
We also set these properties to child by property name as justify-self and align-self and set their values to center and end according to our need.