likes
comments
collection
share

CSS布局方案-高度为宽度百分比

作者站长头像
站长
· 阅读数 20

使用场景

某个元素的高度需要按照宽度的百分比进行设置。

比如元素A的宽度是父元素B的33.33%,并且要求A是正方形的展示区域的时候,就可以用这个方案。

解决方案

<html>
  <body>
    <style>
      .outter {
        width: 500px;
        height: 300px;
        background: black;
      }

      .inner {
        width: 95%;
        padding-bottom: 50%;
        background: grey;
        position: relative;
      }

      .content {
        width: 100%;
        height: 100%;
        position: absolute;
        background: white;
      }
    </style>
    <div class="outter">
      <div class="inner">
        <div class="content">
          <div>test content</div>
          <div>test content</div>
        </div>
      </div>
    </div>
  </body>
</html>

思路说明

outter可以理解为任意一个宽高固定的元素,比如我们 body下的容器我们经常会使用 vw/ vh来根据视区设置宽高。

inner作为容器来控制展示区的大小,其作用是提供一个高度=宽度*百分比的区域。

content作为内容的展示区,以保证 content中的内容,都是展示在 inner这个区域里。

为什么这样做?


解决某些情况下 content内使用其他组件导致样式错位。

开发成组件时,展示区域大小只需要在外部根据实际情况进行调整,而内部无需担心样式问题。

————看懂代码可跳过下面————

代码分析

这部分是拆解代码,节省读者自己写代码的时间。

设定容器大小

首先是创建一个有具体宽高的区域。

<style>
  .outter {
    width: 500px;
    height: 300px;
    background: black;
  }
</style>
<div class="outter">
</div>

就得到了这么一块黑色区域:

CSS布局方案-高度为宽度百分比

设定展示区域

<style>
      .outter {
        width: 500px;
        height: 300px;
        background: black;
      }
      
+ 		.inner {
+       width: 90%;
+       padding-bottom: 50%;
+       background: grey;
+     }
    </style>
    <div class="outter">
+     <div class="inner">
+     </div>
    </div>

效果:

CSS布局方案-高度为宽度百分比

这样我们就得到了一个高度为父元素50%的区域。

添加内容区域

<html>
  <body>
    <style>
      .outter {
        width: 500px;
        height: 300px;
        background: black;
      }
      
      .inner {
        width: 50%;
        padding-bottom: 50%;
        background: grey;
      }

+     .content {
+       width: 100%;
+       height: 100%;
+       background: white;
+     }
    </style>
    <div class="outter">
      <div class="inner">
+       <div class="content"></div>
      </div>
    </div>
  </body>
</html>

这样写 content会按照父元素的宽高进行设置,出来的效果是这样:

CSS布局方案-高度为宽度百分比

修复上面的问题

<html>
  <body>
    <style>
      .outter {
        width: 500px;
        height: 300px;
        background: black;
      }
      
      .inner {
        width: 50%;
        padding-bottom: 50%;
        background: grey;
+       position: relative;
      }

      .content {
        width: 100%;
        height: 100%;
        background: white;
+       position: absolute;
      }
    </style>
    <div class="outter">
      <div class="inner">
        <div class="content"></div>
      </div>
    </div>
  </body>
</html>

效果:

CSS布局方案-高度为宽度百分比

至此就可以在 content中进行内容的开发了。