Friday, 19 June 2020

CSS Flex Layout and Alignment

Justify Content Vs Align Items

Before we get started , Let's first understand what is a flex-direction  because justify-content and align-items are dependent on its value.

It can have two values: row & column

flex-direction: row

If the flex-direction of the container is row, it's children will be placed one after the other horizontally. Meaning, the primary axis is x-axis. Let's visualize this. I have two loop icon divs inside a body container. The container has the flex-direction set to row. Here's how it will appear:




What if i give the property justify-content:center to the container?


You guessed it right. The icons are now moved to the center of the x-axis.

Let me remove justify-content property and add another CSS property to the container :- align-items:center and see what happens:



The icons are now placed in the center of the y-axis.

What if i add both the properties (justify-content:center , align-items:center) to the container?



The icons are placed in the center of both x-axis and y-axis.


flex-direction: column

If the flex-direction of the container is column, it's children will be placed one after the other vertically. Meaning, the primary axis is now y-axis.




Now justify-content:center will place the icons in the center of y-axis as it is the primary axis. and align-items:center will place them in the center of x-axis


 
 
  

justify-content:center
 

align-items:center




(justify-content:center , align-items:center)


CHEATSHEET:



 flex-direction     primary axis     justify-content     align-items    
 row x-axis x-axis     y-axis    
 column y-axis y-axis x-axis



POINT TO REMEMBER:

justify-content acts on primary axis.


No comments:

Post a Comment

JS Animation for Beginners

Simple Spinner Animation The Start and Stop Spinner app example given in MDN docs (  Go to example  ) has one drawback. When you s...