Vertically center in viewport using CSS
What's that? Taking 8 years to get the answer to a problem is too much?
Well, better late than never!
You got really close to the solution. I'd do it with transform: translate()
:
#nav {
position: fixed;
right: 0;
top: 50%;
transform: translateY(-50%);
}
According to Can I use?, it is supported by everything except for IE8- and Opera Mini (which, to be honest, is a pretty good support).
I'd recommend you overkill it a bit and just add all of the vendor prefixes (just to make sure!):
#nav {
position: fixed;
right: 0;
top: 50%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
Here's a snippet to show it to you in action:
#nav {
right: 0;
top: 50%;
position: fixed;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
background-color: #ccc;
padding: 20px;
}
<div id="nav">
ABC<br/>
DEFGH<br/>
IJKLMNO<br/>
PQRS<br/>
TUVWXYZ
</div>
Hopefully it's still relevant to you! (who am I kidding, it's been 8 years)
you can use this as one of the solution.
<style>
#containter {
height: 100vh; //vh - viewport height
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#content {}
</style>
<div id="containter">
<div id="content">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
If the item is set to
position: fixed
orposition: absolute
:top: 50%; left: 50%; transform: translate(-50%, -50%)
If the item is set to
position: relative
, use:margin-top: 50%; margin-left: 50%; transform: translate(-50%, -50%)
(More info at the source.)
Example:
Run the snippet and then resize this page (or rotate device). The box stays centered in the "snippet viewport".
.myContainer {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 5px solid RebeccaPurple;
}
.myThing {
width: 100px;
height: 100px;
background-color: CornflowerBlue;
}
<div class="myContainer">
<div class="myThing myContents">
</div>
</div>