css百分比单位的参照对象

893 阅读1分钟

结论

一般情况下:盒子的宽/高度的百分比是父盒子的宽/高的比;外边距和和内边距都是父盒子宽的比;

html代码

    <div class="parentBox">
        <div class="box">
            <div class="childBox"></div>
        </div>
    </div>

css代码

.parentBox{
    width: 300px;
    height: 400px;
    background-color: rgb(121, 125, 189);
    margin: 4rem auto;
}
.box{
    width: 50%;
    height: 50%;
    margin: 50%;
    padding: 30%;
    background-color: red;
    border:10px solid hsla(240,100%,50%,0.5);
}

.childBox{
    width: 50%;
    height: 50%;
    margin: 50%;
    padding: 30%;
    background-color: rgb(53, 16, 219);
    border:10px solid hsla(240,100%,50%,0.5);
}

浏览器展示结果

box : width:150px;height:200px; margin:150px;padding:90px;

childBox:width:75px;height:100px;margin:75px;padding:45px;