CSS get height of screen resolution

后端 未结 9 1268
后悔当初
后悔当初 2020-12-02 12:10

I\'m having a hard time getting the height of lower screen resolution because my screen resolution is 1920x1080.

Does anyone know how to get height and width of the

9条回答
  •  日久生厌
    2020-12-02 12:57

    You can get the window height quite easily in pure CSS, using the units "vh", each corresponding to 1% of the window height. On the example below, let's begin to centralize block.foo by adding a margin-top half the size of the screen.

    .foo{
        margin-top: 50vh;
    }
    

    But that only works for 'window' size. With a dab of javascript, you could make it more versatile.

    $(':root').css("--windowHeight", $( window ).height() );
    

    That code will create a CSS variable named "--windowHeight" that carries the height of the window. To use it, just add the rule:

    .foo{
        margin-top: calc( var(--windowHeight) / 2 );
    }
    

    And why is it more versatile than simply using "vh" units? Because you can get the height of any element. Now if you want to centralize a block.foo in any container.bar, you could:

    $(':root').css("--containerHeight", $( .bar ).height() );
    $(':root').css("--blockHeight", $( .foo ).height() );
    
    .foo{
        margin-top: calc( var(--containerHeight) / 2 - var(--blockHeight) / 2);
    }
    

    And finally, for it to respond to changes on the window size, you could use (in this example, the container is 50% the window height):

    $( window ).resize(function() {
        $(':root').css("--containerHeight", $( .bar ).height()*0.5 );
    });
    

提交回复
热议问题