CSS get height of screen resolution

后端 未结 9 1247
后悔当初
后悔当初 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:55

    You can bind the current height and width of the screen to css variables: var(--screen-x) and var(--screen-y) with this javascript:

    var root = document.documentElement;
    
    document.addEventListener('resize', () => {
      root.style.setProperty('--screen-x', window.screenX)
      root.style.setProperty('--screen-y', window.screenY)
    })
    

    This was directly adapted from lea verou's example in her talk on css variables here: https://leaverou.github.io/css-variables/#slide31

    0 讨论(0)
  • 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 );
    });
    
    0 讨论(0)
  • 2020-12-02 12:59

    To get the screen resolution use should use Javascript instead of CSS: Use screen.height for height and screen.width for width.

    0 讨论(0)
提交回复
热议问题