傳統方法正方形用固定的形式寫 直接長=寬寫固定的值如下
-
.box{
-
width: 200px;
-
height: 200px;
-
background: pink;
-
color: #666;
-
}

但是很多情況下,在移動端的設計里,圖片的寬度隨着不同的移動設備進行改變的,這個時候就需要用到自適應的正方形的實現。
下面介紹兩種比較簡單的實現方法:
方法一:CSS3 vw 單位,vw是相對於視口的寬度。視口被均分為100單位的vw。1vw = 1% viewport width
-
.box{
-
width: 20%;//width:20vw也可以
-
height: 20vw;
-
background: pink;
-
}
方法二:設置盒子的padding-bottom樣式,讓盒子的padding-bottom和盒子的寬度一樣,同時設置heigh = 0px;
-
-
<html>
-
<head>
-
<meta charset="utf-8">
-
<meta http-equiv="X-UA-Compatible" content="IE=edge">
-
<title></title>
-
<link rel="stylesheet" href="">
-
</head>
-
<style>
-
*{
-
margin: 0;
-
padding: 0;
-
}
-
.box{
-
width: 20%;
-
/* 設置height為0 ,避免盒子被內容撐開多余的高度 */
-
height: 0px;
-
/* 把盒子的高撐開,
-
和width設置同樣的固定的寬度或者百分比 ,
-
百分比相對的是父元素盒子的寬度 */
-
padding-bottom: 20%;
-
background: pink;
-
color: #666;
-
}
-
</style>
-
<body>
-
<div class="box">
-
<p> 這是一個自適應的正方形</p>
-
</div>
-
</body>
-
</html>

要注意的是,如果這里沒有寫height:0px;當盒子里面有內容的時候,盒子會被內容撐大

如果把padding-bottom改成padding-top會出現什么現象?

可以看出來在正方形中有內容的時候,內容會現實在正方形外面,這是因為默認文字是從左到右,從上到下的排列,所以paddin-top以后文字會在正方形外面,所以這里的paddin-bottom和padding-top並不能混用
另外因為盒子設置了heigh:0px;導致該元素里面再有子元素的時候,就無法正常設置高度。所以我們需要用到position: absolute;使當前內容脫離文檔流,那么內容的高度百分比參照的就是父級的寬度
-
*{
-
margin: 0;
-
padding: 0;
-
}
-
.box{
-
width: 20%;
-
/* 設置height為0 ,避免盒子被內容撐開多余的高度 */
-
height: 0px;
-
/* 把盒子的高撐開,
-
和width設置同樣的固定的寬度或者百分比 ,
-
百分比相對的是父元素盒子的寬度 */
-
padding-bottom: 20%;
-
background: pink;
-
color: #666;
-
position: relative;
-
overflow: hidden;
-
}
-
p{
-
position: absolute;
-
width: 100%;
-
height: 100%;
-
background: yellow;
-
}

這樣子盒子里面的內容就把正方形占滿啦
