实现一个子div,要求边长等于父div宽度的一半
一、若父div是window的话,可以用vm单位(1vw = 1% viewport width)
<style>
.box{
width: 50vw;
height: 50vw;
background-color: red;
}
</style>
<body>
<div class="box">
<!-- <div class="margin"></div> -->
</div>
<script>
二、父div是一个不知道长款的div(这里为了方便,我还是把长宽写出来了,其实是未知的)
<style>
.box{
width: 500px;
height: 700px;
background-color: red;
}
.margin{
width: 50%;
padding-bottom: 50%;/* padding百分比相对父元素宽度计算 */
background-color: skyblue;
}
</style>
<body>
<div class="box">
<div class="margin"></div>
</div>
</body>
此时子div的宽度为250px,高度为0,这个蓝色的长度是他的padding-bottom撑起来的。