在實(shí)現(xiàn)元素自適應(yīng)屏幕大小之前,我們先來介紹一個(gè)css知識點(diǎn)。
元素的margin和padding屬性的值(無論是上下邊距還是左右邊距)如果設(shè)置為百分比,都是以寬度為基準(zhǔn)計(jì)算的。
也就是說,在已知寬高比的情況下,css雖然不能確定height的值,但是可以確定padding-top等屬性的值。
實(shí)現(xiàn)思路:
1、算出寬高比(高 / 寬),并設(shè)置為padding-top的值,height設(shè)置為0(由padding-top撐起元素的高度)。
2、此時(shí)元素的實(shí)際內(nèi)容被擠到了下方,所以用絕對定位改變其位置。
(視頻教程推薦:css視頻教程)
實(shí)現(xiàn)代碼:
html代碼:
<div class="ac_coupon-wrap"> <div class="ac_coupon-content"> <!-- 內(nèi)容 --> </div> </div>
css代碼:
.ac_coupon-wrap { height: 0; padding-top: 15.16%; position: relative; .ac_coupon-content { position: absolute; top: 0; width: 100%; height: 100%; background-size: cover; } }
推薦教程:css快速入門