Flex and Grid in CSS3
What is Flex Box?
CSS3 layout provides us easy and clean way to arrange items within a container. CSS3 provides us with flex-box to overcome the block model used in CSS.
- No math is required in arranging items. No Floats
- Responsive and mobile friendly. You can use media query to make things work better.
- Positioning child element is much easier.
- Flex container’s margins do not collapse with the margins of its contents.
- Order of the elements can easily be changed without editing the source HTML.
FLEX BOX MODEL CONCEPT
- The ability to alter item width and height to best fit in its containers available free space.
- Flex-box is direction-agnostic.
- Built for small-scale layouts while the “Grid” specification is for more large scale.
In CSS as we assign display property as flex. The red box in the diagram is the flex-container which is created. The items in the containers are flex items. The x-axis is called main axis which starts form main start to main end and the y-axis is called cross axis which start from cross start to cross end.
FLEX PROPERTIES
- display: flex | inline-flex;
- flex-direction: row | column;
- flex-wrap: wrap | nowrap | wrapreverse;
- flex-basis: <length>;
- justify-content: flex-start | flex-end | center | space-around | space-between;
- align-self: flex-start | flex-end | center;
- align-items: flex-start | flex-end | center;
- align-content: flex-start |flex-end | center;
- flex-grow: <number>;
- flex-shrink: <number>;
- flex: <integer>;
- order: <integer>;
We can move flex-items where we want using order property. We can align items . We can give direction to our flex i.e row or column.
What is Grid?
In flex-box model we can work with rows and column individually but in grid we can work rows and columns in together. CSS grid is the most powerful tool available. Flex-box is one dimensional while grid is two dimensional.
Use Flexbox for UI elements, but use grid for major layouts.
Grid Properties
- grid-template-rows
- grid-template-columns
- grid-template-areas
- grid-auto-rows
- grid-auto-columns
- grid-auto-flow