【问题标题】:How to set an element's height relative to the screen size如何设置元素相对于屏幕尺寸的高度
【发布时间】:2020-05-03 23:19:26
【问题描述】:

我想将元素的height设置为全屏模式尺寸的百分比,这样当浏览器窗口较小时,高度不会改变。

【问题讨论】:

标签: javascript html css fullscreen viewport-units


【解决方案1】:

% 操作符是动态的,它会根据屏幕的宽度或高度而变化 因此,如果您希望长度不会改变,您可以使用pxpt 甚至rem(但这取决于根元素的大小)

height:100%;

2021 年更新

您可以使用vh(视口高度)这将自动调整到屏幕高度

height:100vh;

【讨论】:

    【解决方案2】:

    您可以在vh 中指定height,它相当于视口(不是屏幕)初始包含块高度的1%。

    如果您确实需要 height 相对于屏幕高度,那么您必须使用 JavaScript 的 screen 对象:

    window.screen.height;
    window.screen.width;
    

    您可以直接在style 属性中使用这些值:

    // 10% of the screen height:
    document.getElementById('container')
      .style.height = `${ window.screen.height * 0.1 }px`;
    #container {
      width: 100%;
      border-bottom: 3px solid black;
      
      /* Fallback value (relative to viewport, not screen) */
      height: 10vh;
    }
    <div id="container"></div>

    或者使用calc()CSS custom properties 创建更可重用的东西:

    document.documentElement.style.setProperty(
      '--container-height', `${ window.screen.height }px`);
      
    document.documentElement.style.setProperty(
      '--container-width', `${ window.screen.width }px`);
    :root {
      /* We use thew viewport's dimensions as fallback values: */
      --screen-height: 100vh; 
      --screen-width: 100vw; 
    }
    
    #container {
      width: 100%;
      border-bottom: 3px solid black;
      
      /* 10% of the screen height: */
      height: calc(0.1 * var(--container-height));
    }
    <div id="container"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      相关资源
      最近更新 更多