CSS-Styles Flexbox

The CSS3 Flexbox is a layout that allows responsive elements within a container to be automatically arranged depending on viewport size.


Flexbox examples to learn by doing; please note we will be utlizing TailwindCSS classes.

For these next code examples we have a container & 3 children


Ex. 1: only the container has the display:flex

So as we see the the children are now on the same row not all stacked if we didn't use the flex attributes.


Div 1
2nd Div
3rd div
1<div className='flex w-full bg-pink-400'>
2  <div className='bg-orange-300 text-black'>Div 1</div>
3  <div className='bg-blue-400 text-black'>2nd Div</div>
4  <div className='bg-green-400 text-black'>3rd div</div>
5</div>

Ex. 2: Container has the display:flex && children have flex-1 specifically: flex: 1 1 0%

Div 1
2nd Div
3rd div
1<div className='flex w-full'>
2  <div className='flex-1 bg-orange-300 text-black'>Div 1</div>
3  <div className='flex-1 bg-blue-400 text-black'>2nd Div</div>
4  <div className='flex-1 bg-green-400 text-black'>3rd div</div>
5</div>

Ex. 3: Let's take a look at flex-direction column. Adding the flex-direction: column; will make the children div's to stack

Div 1
2nd Div
3rd div
1<div className='flex flex-col w-full'>
2  <div className='flex-1 bg-orange-300 text-black'>Div 1</div>
3  <div className='flex-1 bg-blue-400 text-black'>2nd Div</div>
4  <div className='flex-1 bg-green-400 text-black'>3rd div</div>
5</div>

Ex. 4: Let's take a look at flex with percent inside a child. Instead of just flex-1 we can use a percent:

Div 1
2nd Div
3rd div
1<div className='flex flex-col w-full'>
2  <div className='flex-[10%] bg-orange-300 text-black'>Div 1</div>
3  <div className='flex-[80%] bg-blue-400 text-black'>2nd Div</div>
4  <div className='flex-[10%] bg-green-400 text-black'>3rd div</div>
5</div>

Ex. 5: Let's take a look aligning. Adding the justify-content: center; will align horizontally & items-center will align vertically:

Simple justify-center example


justify-center(horizontally)
1<div className='flex justify-center h-20 w-96 bg-orange-300 text-black'>
2  justify-center(horizontally)
3</div>

Simple align-items: center; example


items-center(vertically)
1<div className="flex items-center h-20 w-96 bg-orange-300 text-black">
2  items-center(vertically)
3</div>

Simple justify-content: flex-end; to right justify


justify-content: flex-end
1<div className="flex justify-end h-20 w-96 bg-orange-300 text-black">
2  justify-content: flex-end
3</div>

Ex. 6: Let's take a look aligning & centering in a nested flexbox. Adding the flex-direction: column; will make the children div's to stack

Div 1
2nd Div
3rd Div
1<div className='flex flex-col w-full'>
2  <div className='flex-1 bg-orange-300 text-black'>Div 1</div>
3  <div className='flex-1 bg-blue-400 text-black'>2nd Div</div>
4  <div className='flex-1 bg-green-400 text-black'>3rd div</div>
5</div>