# CSS实现自适应正方形和矩形

# 正方形

方法1:使用CSS3 vw 单位,vw是相对于视口的宽度。视口被均分为100单位的vw。1vw = 1% viewport width

<style type="text/css">
	.box{
		background: red;
		width: 30vw;
		height: 30vw;
	}
</style>
<div class="box"></div>
1
2
3
4
5
6
7
8

方法2:设置盒子的padding-bottom样式,让盒子的padding-bottom和盒子的宽度一样,同时设置heigh=0

<style type="text/css">
	.box{
		background: red;
		width: 30%;
		height: 0; /* 设置height为0 ,避免盒子被内容撑开多余的高度 */
		padding-bottom: 30%; /* 利用padding-bottom把元素的高度撑开,设置和width一样的百分比*/
	}
</style>
<div class="box">
	<p>这是一个自适应的正方形</p>
</div>
1
2
3
4
5
6
7
8
9
10
11

# 矩形

实现自适应长宽比为16:9的矩形,假设宽100%,那么高为h=9/16=56.25%,设置padding-bottom为56.25%。

<style>
    *{
        margin: 0px;
        padding: 0px;
    }
    /* .wrap 是包裹矩形的div,用来控制矩形的大小 */
    .wrap{
        width: 20%;
    }
    /* .box 是矩形div */
    .box{
        width: 100%; /*宽度是.wrap的百分百,这主要是为了方便高度的计算 */
        height: 0px;    /*防止矩形被里面的内容撑出多余的高度*/
        /* 16:9 padding-bottom:56.25%,4:3 padding-bottom:75% */
        padding-bottom: 56.25%;  /* 宽度的 56.25% */
        position: relative;
        background: pink;
    }
    /* 矩形里面的内容 ,要设置position:absolute,才能设置内容高度100%和矩形一样 */
    .box p{
        width: 100%;
        height: 100%;
        position: absolute;
        color: #666;
    }
</style>
<body>
    <div class="wrap">
        <div class="box">
            <p>&nbsp;&nbsp;这是一个16:9的矩形</p>
        </div>
    </div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Last Updated: 5/2/2020, 2:51:33 PM