When I drag-drop an image to Chrome or Firefox, the browser nicely sizes the image (if needed) and places it on the center of the screen.
E.g. https://fastly.picsum.photos/id/382/200/300.jpg?hmac=ql7Jj1WJu3zhhAn2p18Oxdn-JE1qZBR-lDF-MOVXCUA
(link of a random image from picsum.photos - this simulates the drag drop to the browser window, as the browser applies the styles etc.)
A screenshot of the Chrome Devtools below (notice the top and bottom margins on the image)
However, when I try to use the exact same layout styles on my own html page to show the very same image, the image is not getting vertically center aligned. (View on Full page after running code snippet)
E.g.
<html style="height: 100%;">
<head>
<meta name="viewport" content="width=device-width, minimum-scale=0.1">
<style>
body {
margin: 0px;
height: 100%;
/* background-color: rgb(14,14,14); */
}
img {
display: block;
margin: auto;
user-select: none;
}
</style>
</head>
<body>
<img src="https://fastly.picsum.photos/id/382/200/300.jpg?hmac=ql7Jj1WJu3zhhAn2p18Oxdn-JE1qZBR-lDF-MOVXCUA" alt="">
</body>
</html>
(I purposely left the background white to distinguish my page vs browser page)
I checked and re-checked that I had all the appropriate layout styles, but still not able to get the image aligned vertically. Any pointers?
Thanks!
When a browser is displaying a simple image, it can display it however it wants to. But when it is displaying a web page, it has to follow the layout rules for web pages, and those rules are that the contents of a web page are laid out starting from the top of the page. If you want a different layout, you as the web designer have to specify that.
Option 1 - Flexbox
html, body {
height: 100%;
}
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
<img src="https://fastly.picsum.photos/id/382/200/300.jpg?hmac=ql7Jj1WJu3zhhAn2p18Oxdn-JE1qZBR-lDF-MOVXCUA">
Read more about flexbox and centering elements using flexbox.
Option 2 - Fixed positioning
img {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
<img src="https://fastly.picsum.photos/id/382/200/300.jpg?hmac=ql7Jj1WJu3zhhAn2p18Oxdn-JE1qZBR-lDF-MOVXCUA">
Read more about centering elements using fixed positioning.