【问题标题】:Dynamically adjust the height of an elements so they always stick to a single page动态调整元素的高度,使它们始终保持在单个页面上
【发布时间】:2019-07-04 12:52:22
【问题描述】:

我的页面上有几个元素

我希望能够根据屏幕高度动态更改AB 的高度,以便AB 元素始终保持在单个屏幕上而无需向下滚动。

目前我正在使用媒体查询来调整元素的高度

@media screen and (min-width: 1920px) and (max-width: 5000px) {
  .A{
    height: 600x;
  }
  .B{
    margin-right: 400px;
  }
}

@media screen and (min-width: 1279px) and (max-width: 1919px) {
  .A{
    height: 550px;
  }
  .B{
    height: 350px;
}

但是这个解决方案有点傻,因为我更喜欢 AB 的高度根据当前高度动态变化,而不需要为每个屏幕尺寸编写太多媒体查询,因为这可能很多.

有什么聪明的解决方案吗?

【问题讨论】:

    标签: css sass responsive-design


    【解决方案1】:
      <!-- language: lang-css -->
        try this one
    
        * {
           margin:0;
           padding:0;
           box-sizing:border-box;
         }
    
         .container {
              height: 100vh; // this can gives (.container) height according to view screen
          }
    
         .a{
             height: calc(60vh - 40px);//minus the header height
           }
    
          .b{
             height: calc(40vh - 60px); //minus the footer height
            }
    
    
    
    <!-- language: lang-html -->
    
        <div class="container">
          <header>header</header>
          <div class="a">A</div>
          <div class="b">B</div>
          <footer>footer</footer>
        </div>
    

    【讨论】:

      【解决方案2】:

      我们可以使用 Flexbox 以柱状方向解决这个问题。

      • 由于您在原始代码中使用了600px/400px,因此我分别将64 用作flex-grow.a..b. 值。
      • 这些flex-grow 值是相对的,因此.6.4600 400 将产生相同的结果。
      • headerfooter.ab 占用空间之后占用容器中剩余的空间。

      html, body {
        margin: 0;
      }
      
      .container {
        min-height: 100vh;
        display: flex;
        flex-direction: column;
      }
      
      .container > * {
        padding: .5em;
      }
      
      .a {
        flex-grow: 6;
        background-color: #eee;
      }
      
      .b {
        flex-grow: 4;
        background-color: #ff0;
      }
      <div class="container">
        <header>header</header>
        <div class="a">A</div>
        <div class="b">B</div>
        <footer>footer</footer>
      </div>

      https://jsfiddle.net/j3kxr50L/2/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2012-02-27
        • 2020-10-28
        • 2020-10-06
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        相关资源
        最近更新 更多