如上圖所示,屏幕正中間有個元素A,隨着屏幕寬度的增長,始終須要知足如下條件:css
用html和css實現。html
這道題主要考察css的居中和寬高等比例。其中,居中是css的經典知識點,有不少種實現,我喜歡用transform
屬性來控制。咱們重點來看考察的第二個知識點:css3
在寬度不定的狀況下,保持寬高的比例,這個使用場景比較少。不用js,純CSS應該怎麼實現呢?spa
直覺是想到用css3的calc來解決,行不通。code
若是A元素的高度和寬度都以某一個值做爲參照系,那麼理論上A元素的height = n 乘以 width(n可自定義)。根據css規範,padding的值爲百分比時,是相對於父元素的寬度而言。可見,父元素的寬度就是一個完美的參照系!給A元素包一個父元素,A元素的width爲100%,height爲0,padding-top爲50%。這就實現了A元素的寬高等比例啦~orm
Talk is cheap. Show me the code. 效果預覽htm
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="father"> <div class="son"><span>A</span></div> </div> </body> </html>
.father{ overflow:hidden; position: absolute; left:20px; right:20px; top:50%; transform: translateY(-50%); } .son{ height:0; width:100%; padding-top:50%; background:pink; } span{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); font-size:10px; }