What is CSS Flexbox? Explain with suitable example

In CSS2 we use float property to align our boxes, we can align our boxes left or right, we can’t align our boxes vertically and center. This is a limitation in float property, In CSS3 Flexbox Introduced; by using flex we can align our boxes horizontally or vertically very easily.

CSS3 Flexbox is written in parent element to align child element, it does not use like float, it is a little bit different than other CSS properties.

CSS3 Flexbox has two major properties by using these we can align our boxes:

  • justify-content: justify-content is used to align boxes or any HTML element horizontally (x-axis).
 
justify-content has some properties to align elements horizontally:

  1. flex-start: left aligns element.
  2. flex-end: right aligns element.
  3. center: center aligns element.
  4. space-between: left aligns element with proper space between boxes except for the first box and last box.
  5. space-around: left aligns element with equal space right and left between boxes.
   
  • align-items: align-items is used to align boxes or elements vertically (y-axis).

align-items has some properties to align elements vertically:

  1. flex-start: left aligns element at the top of the container.
  2. flex-end: left aligns element at the bottom of the container.
  3. center: center aligns element vertically.
  4. space-between: left aligns element with proper space between boxes vertically except first box and last box.
  5. space-around: left aligns element with equal space vertically right and left between boxes.
   

Example:

<!DOCTYPE html>
<html>
<head>
 
<style>
.main
{
 width:100%;
 height:1000px;
 background:#eee;
 display:flex;
 justify-content:space-around;
 flex-wrap:wrap;
 align-items:center;
}
 
.box
{
width:300px;
height:300px;
background:#f00;
margin:20px;
}
 
</style>
 
</head>
 
 
<body>
 
<div class="main">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
 
</body>
</html>
 


In this example, we have used justify-content and align-items both to align our boxes horizontally and vertically.

Note: In this example, we have used flex-wrap: wrap property, by default flex, does not wrap boxes in a new line that’s why we have to use the flex-wrap property.

CSS3 Flexbox is modern property to align elements, nowadays mostly web designers use flexbox to align items instead of float.

Categories: web designing css

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo