【问题标题】:Setting CSS top percent not working as expected设置 CSS 最高百分比未按预期工作
【发布时间】:2020-12-12 20:40:12
【问题描述】:

我尝试了一个响应式 css 布局,但是“top:50%”不能工作,而“left:50%”可以。 为什么会这样?

<div style="position:relative;top:0%;left:0%;height:100%;width:100%">
    <div style="position:absolute;top:50%;left:50%;">
    </div>
</div>

【问题讨论】:

  • 您是否为第一个 div 的父容器指定了高度?即身体?
  • 左边在这里工作正常jsfiddle.net/8b9Lny2a你使用的是什么浏览器。
  • 对不起,父 div 的高度和宽度是 100%。似乎大约 100% 的高度不起作用;但是如果我将父 div 设置为指定的 1000px,则会指定子 div 的顶部太...我希望孩子 div'top 响应其父母的身高?这可能吗?
  • 如果父元素设置了高度并且没有使用百分比,则 100% 的高度将起作用。唯一可行的方法是,将一直到 htmlbody 的父母也设置为 100%。

标签: css


【解决方案1】:

为父容器定义一个维度,例如分区:

<div style="border: 2px solid red;position:relative;top:0%;left:0%;height:200px;width:300px">
    <div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
    </div>
</div>

或者

另一种方法是仅通过其顶部、底部、左侧和右侧属性拉伸父容器,即 div。像这样:

<div style="border: 2px solid red;position: absolute;top: 0px;bottom: 0px;left:0px;right:0px;">
    <div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
    </div>
</div>

【讨论】:

    【解决方案2】:

    考虑您的原始 HTML:

    html, body {
      height: 100%;
    }
    <div style="position:relative;top:0%;left:0%;height:100%;width:100%">
      <div style="position:absolute;top:50%;left:50%;">test</div>
    </div>

    inner/child divposition: absolute,所以它不在父元素的内容流中,不会对父元素的高度或宽度有贡献。

    div在内容流中,但没有内容,所以它的内在 高度将为零。但是,您指定了height: 100%,但这不会做任何事情,因为div 没有作为计算值基础的高度参考。因此父级div 的计算高度值为零。

    因此,子元素的 top 偏移量计算为 50% 为零, 所以它位于父块的顶部边缘。

    您需要为父级 div 指定高度或分配

    html, body {height: 100%} 
    

    因为这将允许 div 根据高度计算其高度 body,根据html的高度,取屏幕高度为100%。

    【讨论】:

      【解决方案3】:

      请参阅下面的链接。我相信你会因为你想要做的事情而得到更好的结果,尽管我仍然不能 100% 确定我理解那是什么。

      http://jsfiddle.net/8q107wvb/1/

      body {background:#e9e9e9; color:#202020;}
      #wrapper {width:500px; background:#fff; margin:50% auto;}
      .centered-content {position: fixed; top: 50%; left: 50%; background:#fff; padding:20px;}
      

      【讨论】:

        【解决方案4】:

        这是另一个解决这个问题的方法

        * {
          height: 100%;
        }
        .first{  
          position:relative;
          top:0%;
          left:0%;height:100%;
          width:100%"
        }
        div{
          position:absolute;
          top:50%;
          left:50%;
        }
        
        <div class="first">
          <div style=>Check this</div>
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-12
          • 2018-09-12
          • 1970-01-01
          相关资源
          最近更新 更多