How to useGrid in CSS
To center an image along the X-axis and Y-axis, use a “grid” and wrap up the image into a div container and define some height if you are using it alone to center an image. After that define “justify-content” to “center” along X-axis i.e. Horizontally and “align-items” to “center” along Y-axis (Vertically).
Syntax for Grid Positioning:
display: grid;
justify-content: center;
align-items: center;
Example: Illustration of making an Image Center Vertically and Horizontally Using Grid
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Center Image horizontally and vertically</ title > < style > body { background-color: rgb(236, 220, 251); } .container { height: 100vh; display: grid; justify-content: center; align-items: center; } </ style > </ head > < body > < div class = "container" > < img src = "https://media.w3wiki.org/wp-content/uploads/20240222161742/gfgimage.png" alt = "Your Image" /> </ div > </ body > </ html > |
Output:
How to Center an Image Vertically and Horizontally ?
To center an image along X-axis i.e. Horizontally and along Y-axis i.e. vertically we can use different CSS properties.
There are different ways to center an Image Vertically and Horizontally including CSS flexbox properties, absolute positioning, and CSS Grid System.
Table of Content
- Using Flexbox
- Using Absolute Positioning
- Using Grid