如何使用 CSS 创建自适应的正方形?
介绍三种方法:padding-bottom 技巧、vw/vh 单位和 Flexbox 布局,用于创建根据父容器或视口大小自动调整的正方形。
有多种方法可以使用CSS实现一个自适应正方形,使其宽度和高度保持一致,并且根据父容器或视口响应式调整尺寸。
-
使用 padding-bottom 技巧
此方法基于 CSS 的 padding 百分比值相对于父元素宽度计算的特性,通过设置 padding-bottom 为与宽度相同的百分比,结合 position 控制子元素位置,实现正方形结构。优点是兼容性好。<!DOCTYPE html> <html lang="en"> <head> <style> .container { width: 25%; /* 任何百分比宽度,定义正方形大小相对于父元素 */ height: 0; /* 强制设置高度为0 */ padding-bottom: 25%; /* padding-bottom 值等于宽度比例值 */ position: relative; /* 作为子元素定位参考 */ } .square { position: absolute; /* 绝对定位填充 container */ top: 0; right: 0; bottom: 0; left: 0; background-color: skyblue; /* 可视效果 */ } </style> </head> <body> <div class="container"> <div class="square"></div> <!-- 正方形区域 --> </div> </body> </html>
-
使用 vw/vh 单位
此方法利用相对于视口的视口单位(如 vw),可直接设置 height 属性基于视口宽度比例创建正方形。优点是在简单场景下编码简洁。.square { width: 25vw; /* 25%视口宽度,适合移动端 */ height: 25vw; /* 等于宽度值 */ background-color: pink; }
注意:在移动端兼容性好,但 IE10 及以下浏览器不支持。也可用百分比,如
width: 50%; height: 50vw
。 -
使用 Flexbox 布局
适用需要复杂布局时,通过设置 flex 容器的 align-items 确保子元素强制正方形。适合在 flex 网格或居中场景中。<style> .flex-container { display: flex; justify-content: center; align-items: stretch; /* 使子元素默认拉伸匹配高度 */ } .square { width: 25%; aspect-ratio: 1/1; /* 简化方式:设置宽高比 */ background-color: lightblue; } </style> <div class="flex-container"> <div class="square"></div> </div>
现代浏览器支持
aspect-ratio
直接设置宽高比。
其他注意事项:
- 所有方法需考虑父容器:如果父元素动态改变宽度,子元素会自动缩放。
- 推荐优先用 padding-bottom 技巧获得最佳浏览器支持;vw 在移动响应式中更直接。
- 避免同时设置 height:100%,因为 height 百分比基于父元素高度计算(非宽度),可能破坏正方形比例。