CSS实现一个正方形,正方形的宽度为父元素的50%

首先正方形的宽度应该是50%

方法一:用padding-bottom

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<style>
div.parent
{
    width:288px;
    background-color:yellow;
}
.child{
    width:50%;
    padding-bottom:50%;
    height:0;
    background-color:#ccc;
}
</style>
</head>
<body>
<div class='parent'>
    <div class='child'></div>
</div>
</body>
</html>

效果如下图

父元素如果加上高度,效果如下

方法二:使用CSS3的viewpoint width,视窗宽度,1vw=视窗宽度的1%

<html>
<head>
<style>
div.parent
{    height:50vw;
    width:50%;
    background-color:yellow;
}
.child{
    height:25vw;
    width:50%;
    background-color:#ccc;
}
</style>
</head>
<body>
<div class='parent'>
    <div class='child'></div>
</div>
</body>
</html>

效果如图:

 

 

  

 

posted @ 2019-03-21 22:44  KevinHoo  阅读(1235)  评论(0)    收藏  举报