主要介绍在Web中如何实现纵横比,主要是用于响应式设计中的iframe、img和video之类的元素。
margin/padding百分比相对于父元素宽度。
使用CSS实现容器长宽比,常见的HTML模板结构如下:
<div class="aspectration" data-ratio="16:9">
<iframe height="498" width="510" src="http://player.youku.com/embed/XMTg0MjQ2NzY3Ng==" frameborder="0" allowfullscreen=""></iframe>
</div>
主要借助的原理是:利用padding-top
或者padding-bottom
的百分比值,实现容器长宽比。
在CSS中padding-top
或padding-bottom
的百分比值是根据容器的width
来计算的。
如此一来就很好的实现了容器的长宽比。
采用这种方法:
height
设置为0
。(容器的高用padding-top
来撑开容器)position:absolute
,不然子元素内容都将被padding
挤出容器(造成内容溢出)。比如我们容器的长宽比是16:9
,那么根据计算:100% * 9 / 16
可以得到56.25%
。如果你希望的是4:3
,那么对应的就是100% * 3 / 4
。
具体的CSS代码如下:
*{margin: 0;padding: 0; list-style: none;}
.aspectration {
position: relative;
height: 0;
}
.aspectration[data-ratio="16:9"] {
padding-top: 56.25%;
}
.aspectration[data-ratio="4:3"]{
padding-top: 75%;
}
.aspectration > * {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #000
}
padding
和calc()
配合在一起使用。padding
的值计算,如果使用calc()
可以通过浏览器直接计算出padding
的百分比值。.aspectration[data-ratio="16:9"] {
padding-top: calc(100% * 9 / 16);
}
.aspectration
元素上使用padding
值。::before
或::after
来撑开容器。.aspectration {
position: relative;
}
.aspectration:after {
content: "";
display: block;
width: 1px;
margin-left: -1px;
background-color: orange;
}
.aspectration[data-ratio="16:9"] {
padding-top: 56.25%;
}
CSS新特性中提供了一种新的单位vw
,浏览器100vw
表示的就是浏览器的视窗宽度(Viewport)。
16:9
对应的就是100vw * 9 / 16 = 56.25vw,这里不再是padding
了,而是把这个值给height
。
.aspectration[data-ratio="16:9"] {
width: 100vw;
height: 56.25vw;
position: relative;
}
[DEMO]
原文:https://www.cnblogs.com/jiajia-hjj/p/14920404.html