[CSS] 等比例寬高(equal width and height, aspect ratio boxed)
Aspect Ratio Boxes @ CSS Tricks
keywords: 等比例寬高縮放, 寬高相等, equal width height, ratio, 動態寬度, dynamic width, aspect ratio boxes
Demo Code
See the Pen CSS Responsive Square (equal width and height) by PJCHEN (@PJCHENder) on CodePen.
Grid Gallery Layout with Bootstrap 4
See the Pen Grid Gallery Layout with Bootstrap 4 by PJCHEN (@PJCHENder) on CodePen.
目錄
[TOC]
等比例縮放的容器搭配內容
觀念
當 padding 設為百分比時,padding-top 和 padding-bottom 的計算是根據該元素的 width 決定的。所以當元素的寬度是 500px 時,使用 padding-top 為 100% 時,padding-top 就會是 500px。
此時若我們將元素的高度設為 0(height: 0;),並且不設定邊框(border-width: 0;),如此 padding 將會是影響 box model 高度的唯一因素。
此時,如果我們需要的是 16:9 的比例時,只需將 padding-bottom 設定成 56.25%(9 / 16 = 0.5625)即可。
這時候我們就有一個可以 RWD 變化 的容器,因為當這個容器的寬度改變時,高度也會連帶跟著改變。
padding-bottom=image-height / image-width * 100%
1. 利用 width = padding-bottom
利用 padding-bottom 可以製作等比例縮放的容器,關鍵在於 「當 padding-bottom 設定為百分比時,它會去抓該層空間的總寬度為分母。」
.responsive-square {
margin: 0 auto;
background-color: $dark-blue;
width: 35%; // 寬佔整個寬度的 35%
padding-bottom: 35%; // 高佔整個寬度的 35%
position: relative;
.content {
color: white; // 將裡面的空間展開成和外面一樣
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0; // 水平垂直置中內容
display: flex;
justify-content: center;
align-items: center;
}
}
2. 利用 :before / :after
.responsive-square-pseudo-element {
margin: 0 auto;
width: 35%; // 決定要佔總寬度多少 %
background-color: steelblue;
position: relative; // 用來協助定位內層元素
&::after {
content: '';
display: block;
padding-bottom: 100%; // 一直都是 100%
}
.content {
@include full-screen;
@include vh-center;
color: white;
}
}
等比例縮放的容器搭配圖片
❗ 圖片的比例也必須要是 1:1。
1. 利用 max-width: 100%
可以直接使用 max-width: 100% 的方式,該圖片就會等比例縮放:
.responsive-max-width-100 {
width: 30%;
margin: 0 auto;
background-color: #ccc;
img {
display: block; /* ★★★★★ */
max-width: 100%; /* ★★★★★ */
}
}
2. 利用 width = padding-bottom
參考
- :thumbsup: Aspect Ratio Boxes @ CSS Tricks
- Learn how to maintain the aspect ratio of an element with CSS @ W3schools