Reputation: 903
So, I need to position my element perfectly to the center. It displays correctly in fullscreen mode, however when it's not in fullscreen mode, the element is moved slightly down due to the top of the browser (tabs, URL bar, etc..)
I am using this CSS:
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
I have a feeling it's centered relative to the screen resolution? (Which explains why it's centered perfectly to fullscreen).
Here are images of what I mean:
https://i.sstatic.net/f63l7.jpg
https://i.sstatic.net/xwNfs.png
Is there any way to fix this? I don't mind using HTML/CSS/JS to solve this issue, I can also use JavaScript libraries.
Thanks for any help!
Edit:
My element is inside the body, like this:
<body>
<img class="centered" src="image.png">
</body>
Upvotes: 0
Views: 69
Reputation: 1036
Make use of the vh
unit by changing your code like so:
.centered {
position: absolute;
top: 50vh;
left: 50%;
transform: translate(-50%, -50%);
}
Upvotes: 1
Reputation: 275
You need to set parent to position: relative
.
.parent {
position: relative;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="parent">
<span class="centered">I am centered</span>
</div>
Upvotes: 0