How to useAbsolute Positioning in CSS
Use absolute positioning of an image to make it center from X-axis and Y-axis. To, position an element “absolute” firstly, position its parent element as “relative“. then, define the position of the image element from the top, left, right, and bottom.
Syntax for absolute positioning:
position: relative;
position: absolute;
Example: Illustration of making an Image Center Vertically and Horizontally using positioning absolute.
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 > .container { height: 100vh; width: 100%; position: relative; } img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 100%; max-height: 100%; } </ style > </ head > < body > < div class = "container" > < img src = 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