天天看點

CSS長寬比CSS長寬比

CSS長寬比

長寬比概念

長寬比在影視制作中又稱為寬高比

是指一個視訊的寬度除以高度所得出的比例

  • 電影工業中最常用的是anamorphic比例(即2.39:1)
  • 傳統的4:3仍然被用于許多電視畫面上
  • 後繼規格16:9被用于高清晰度電視/數字電視
    CSS長寬比CSS長寬比

HTML結構

使用CSS實作容器長寬比,常見的HTML模闆結構有

<div class="aspectration" data-ratio="16:9">
    <div class="content"></div>
</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的正方形

CSS長寬比CSS長寬比

采用這種方法,需要把容器的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