元素保持宽高比

元素保持宽高比

前言

开发常见问题

padding-top/bottom方案

父元素子元素嵌套,父元素是一个固定宽高的正方形,子元素的宽度为100%,高度为0,padding-top/bottom为百分比

.parent{
  width:500px;
  height:500px;
}
.child{
  width:100%;
  height:0;
  padding-top:66%;
}

子元素的padding-top/bottom百分比为纵横比

1/1=100% 1/2=50% 3/4=75% 9/16=56%

aspect-ratio

aspect允许创建保持纵横比的容器

语法

aspect-ratio: auto || <ratio>

auto为默认值 ratio的写法为 <width/height>

  .parent{
    width:500px;
    aspect-ratio:3/4;
  }

vw/vh

由于 vw,vh是相对于视窗的占比,可以在不同的屏幕下保持相通的宽高比

.parent{
  width:40vw;
  height:30vw;
}
元素保持宽高比
https://pic.imgdb.cn/item/65137dbec458853aef1b2d8a.jpg
作者
Firefly
发布于
2026-04-03
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Firefly
Hello, I'm Firefly.
公告
欢迎来到我的博客!这是一则示例公告。
音乐
暂无封面

音乐

暂未播放

0:000:00
暂无歌词
暂无歌曲
分类
标签
站点统计
文章
21
分类
3
标签
13
总字数
57,102
运行时长
601
最后活动
143 天前

目录