CSS长宽比
长宽比概念
长宽比在影视制作中又称为宽高比
是指一个视频的宽度除以高度所得出的比例
- 电影工业中最常用的是anamorphic比例(即2.39:1)
- 传统的4:3仍然被用于许多电视画面上
- 后继规格16:9被用于高清晰度电视/数字电视
HTML结构
使用CSS实现容器长宽比,常见的HTML模板结构有
<div class="aspectration" data-ratio="16:9">
<div class="content"></div>
</div>
<div class="aspectration" data-ratio="16:9"></div>
CSS实现长宽比例方法
垂直方向的padding
这是最早提出的方案,利用padding-top或者padding-bottom的百分比值,实现容器长宽比
CSS中的padding-top和padding-bottom的百分比值是根据容器的width来计算的
padding百分比是相对于父元素的宽度计算的
实现一个正方形
<div class="container">
<div class="box"></div>
</div>
.container {
width:100px;
height:200px;
}
.box {
background-color: #8ec63f;
padding:50%
}
50 * 50 px的正方形
采用这种方法,需要把容器的height设置为0
容器内的所有元素都需要采用position:absolute
不然子元素内容都将被padding挤出(造成内容溢出)
- 容器的长宽比16 : 9 ,计算100% * 9/16 可以得到56.25%
- 容器的长宽比为4 : 3, 计算 100% * 3/4 可以得到75%
.aspectration {
position: relative; /* 容器子元素需要绝对定位 */
height: 0;
width: 100%;
}
.aspectration[data-ratio="16:9"] {
padding-top: 56.25%
}
.aspectration[data-ratio="4:3"] {
padding-top: 75%
}
通过通配符*选择器,让其子元素的宽高与容器.aspectration
一样大小
.aspectration > * {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
padding & calc()
这种方案采用padding和calc()配合在一起使用
原理和上面的一样,不同的是上面每次都需要对padding值计算
使用calc()可以通过浏览器直接计算出padding的百分比值
.aspectration[data-ratio="16:9"] {
padding-top:calc(100% * 9 / 16);
}
.aspectraion[data-ratio="4:3"] {
padding-top:calc(100% * 3 / 4 );
}
padding & 伪元素
前面的方法都是在.aspectration元素上使用padding值
还可以使用CSS的伪元素 ::before或者::after来撑开容器
.aspectration {
position: relative;
}
.aspectration:after {
content:"";
display:block;
width:1px;
margin-left:-1px;
background-color:orange;
}
.aspectration[data-ratio="16:9"]:after {
padding-top:56.25%;
}
.content {
width: 100%;
height: 100%;
position: absolute;
top:0;
left:0;
}
视窗单位
CSS新特性中提供了一种新的单位vw
浏览器100vw
表示的是浏览器的视窗宽度(ViewPort)
- 视窗(ViewPort)是你的浏览器实际显示内容的区域——也就是不包括工具栏和按钮的网页浏览器
比如你的浏览器是1334px,那么对应的100vw = 1334px 这时1vw = 13.34px
这里的100vw对应前面方案的100%,把前面的%单位换成vw单位
- 16 : 9 对应的是 100vw * 9 / 16 = 56.25vw
- 4 : 3 对应的是 100vw * 4 / 3 = 75vw
.aspectration[data-ratio="16:9"] {
width: 100vw;
height: 56.25vw
}
如果上面的示例中width
的值是30vw
那么对应的height
值就是30vw * 9 / 16 = 16.875vw
= 75vw
.aspectration[data-ratio="16:9"] {
width: 100vw;
height: 56.25vw
}
如果上面的示例中width
的值是30vw
那么对应的height
值就是30vw * 9 / 16 = 16.875vw
参考资料:
https://www.cnblogs.com/love314159/articles/9797191.html
https://www.xp.cn/b.php/84647.html
https://www.cnblogs.com/qianxunpu/p/8303228.html