寬高等比縮放

容器寬高等比,就是根據容器的寬度,按照寬高比例自動計算出容器的大小。而且讓圖片,視頻之類能自適應容器。
實現方式:垂直方向的paddingurl

基於容器的widthpadding一個百分比。主要的原理是基於元素的padding-toppadding-bottom是根據元素的width進行計算的。spa

假設你有一個div容器,它的寬度是400px,高度爲200px。這個時候藉助padding-top或者padding-bottom的值爲50%。code

根據容器的寬度和padding就能夠計算出容器div的高度是200px。 視頻

1.HTML結構blog

1 <div class="container"> 
2     <div class="content" data-ratio="16:9">
3         <div class="center">
4             <input type="text" placeholder="用戶名">
5             <input type="text" placeholder="密碼">
6         </div>
7     </div> 
8 </div>

上面的HTML結構中,只要的核心內容是content和center。外面的container主要是鋪滿整個頁面的,她沒有進行寬高的等比圖片

<div class="content" data-ratio="16:9"> 

  <div class="center"></div>

  </div>input

詳解:1.content裏面必須包含一個子標籤centerit

           2.全部其餘內容放在子標籤內,不能直接放在content中io

2.CSS代碼class

 1  .container{
 2         height: 100%;
 3         width: 100%;
 4         background: url("imgs/login_bg.png") center no-repeat;
 5         background-size: cover;
 6         padding: 4.93% 0;
 7    }
 8     .content{
 9         position: relative;
10         margin: 0 auto;
11         height: 0;
12         width: 30%;
13         padding-top: calc(30% * 512 / 428);   /*//自身高度/自身寬度*/
14         background: url("imgs/account_bg.png") center no-repeat;
15         background-size: contain;
16         text-align: center;
17     }
18     .content>*{
19         position: absolute; 
20         left: 0; 
21         top: 0;
22         width: 100%;
23         height: 100%
24         
25     }
26     .center{
27         padding: 40% 0;
28 
29     }
30     .content input{
31        padding: 0;
32        margin: 0;
33        width: 50%;    /*自身寬度比上父親寬度*/
34       height: 6.25%;   /*自身高度比上父親高度*/
35        padding-left: 10%;    /*自身寬度比上父親寬度*/
36       margin-top: 10%;    /*自身高度比上父親寬度*/
37       color:#fff;
38       border: none;
39       border-radius: 2px;
40       background-color: rgba(255,255,255,0.3);    
41       margin-bottom: 1.168%
42     }

上面的CSS代碼核心部分以下

 1     .content { 
 2         position: relative; /*由於容器全部子元素須要絕對定位*/ 
 3         height: 0; /*容器高度是由padding來控制,盒模型原理告訴你一切*/ 
 4         width: 100%; 
 5     } 
 6     .content[data-ratio="16:9"] { 
 7         padding-top: cal(200/400)*100%; 
 8     }  
 9     /*經過通配符*選擇器,讓其子元素的寬高和容器.content同樣大小 */
10     .content > * { 
11         position: absolute; 
12         left: 0; 
13         top: 0; 
14         width: 100%;
15         height: 100%; 
16     } 

詳解:1.容器相對定位,寬度100%,高度爲0 ,經過padding-top來顯示高度。padding-top的值是(高度/寬度)*容器的寬度百分比。

           2.經過通配符*選擇器,讓其子元素的寬高和容器.content同樣大小 (center的寬高是100%)

           3.容器裏面的內容,涉及到的單位都用px.

              元素的寬(百分比)=自身寬度/容器(父)的寬*100%;

              元素的高(百分比)=自身高度/容器(父)的高*100%;

              padding/margin=自身大小/容器(父)的寬度*100%。(即,不管是上下的間距仍是左右的間距都是用自身的值/父的寬度)

相關文章
相關標籤/搜索