How to center a <div> using CSS grid Property ?
In this article, we will learn to center an HTML <div> element using the grid property of CSS.
To center the <div> element horizontally using grid. Use the property of display set to grid i.e. display: grid; Then use property place-items: center;
Example: The following example demonstrates to set the <div> to the center using grid property.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < style > .grid{ display: grid; place-items: center; color: green; font-size: 25px; height : 500px; } </ style > </ head > < body > < div class = "grid" > < p >Geeks for Geeks</ p > </ div > </ body > </ html > |
Output:

centre div using height
Example 2: We will demonstrate an example where we are not setting the height for the <div>. The result will be at the center but only in the x-axis direction whereas by setting height we can center <div> on both axis.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < style > .grid{ display: grid; place-items: center; color: green; font-size: 25px; } </ style > </ head > < body > < div class = "grid" > < p >Geeks for Geeks</ p > </ div > </ body > </ html > |
Output:

center on x axis
Please Login to comment...