css计算元素百分比大小

包含块定义:

戳这里客官~

百分比是基于包含块的宽度来确定的

第一种:children设置position为绝对定位,父元素为relative或者为absolute、fixed;则children的百分比大小就是基于parent(为children包含块)的宽度来计算的,宽度长度啥的。

css:

   .parent{
            position: relative;
            width: 400px;
            height: 400px;
        }
        .children{
            position: absolute;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

第二种:parent的position为默认的static,children的position设置为absolute;则children的百分比大小是基于视口的宽度来计算的。children的所有祖先元素的position都是默认的

css:

   .parent{
            width: 400px;
            height: 400px;
        }
        .children{
            position: absolute;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

第三种:设置children的position为relative,则children的百分比大小是基于其最近的块容器(相当于块元素;block、inline-block、list-item、table)的宽度来计算的

css:

   .parent{
            width: 400px;
            height: 400px;
        }
        .children{
            position: relative;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

扫描二维码关注公众号,回复: 1268275 查看本文章
<div class="parent">
    <div class="children"></div>
</div>

第四种:如果children的position设置为fixed;则children的百分比大小是基于视口的宽度来计算的

css:

   .parent{
            position:relative;
            width: 400px;
            height: 400px;
        }
        .children{
            position: fixed;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

猜你喜欢

转载自my.oschina.net/u/3407699/blog/1786349