How to align objects vertically when working with grids in CSS ?
CSS grid layout is one of the strongest layout of CSS. The grid layout is 2-D which means it can handle both rows and columns, unlike flexbox which is 1-D. To align objects apply CSS to the parent element which becomes the grid container and the element’s child which becomes the items in the grid.
Approach:
Use the align-content property of CSS grids to vertically align objects.
Syntax:
align-content: center;
Example 1:
<!DOCTYPE html> < html > < head > < style > .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #4dd599; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </ style > </ head > < body > < div class = "gfg" > < div >Welcome</ div > < div >to</ div > < div >Geeks</ div > < div >for</ div > < div >Geeks</ div > < div >Start</ div > </ div > </ body > </ html > |
Output:
Example 2:
<!DOCTYPE html> < html > < head > < style > .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #f67280; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </ style > </ head > < body > < div class = "gfg" > < div >Explore</ div > < div >the</ div > < div >world</ div > < div >travel</ div > < div >and</ div > < div >eat</ div > </ div > </ body > </ html > |
Output:
Please Login to comment...