Vertically center in viewport using CSS

后端 未结 4 712
一生所求
一生所求 2020-12-06 00:14

I am looking to vertically center a

in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only). I have several const
4条回答
  •  时光说笑
    2020-12-06 00:57

    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;
    }

    Hopefully it's still relevant to you! (who am I kidding, it's been 8 years)

提交回复
热议问题