宽高等比缩放

容器宽高等比,就是根据容器的宽度,按照宽高比例自动计算出容器的大小。并且让图片,视频之类能自适应容器。
实现方式:垂直方向的padding

基于容器的widthpadding一个百分比。主要的原理是基于元素的padding-toppadding-bottom是根据元素的width进行计算的。

假设你有一个div容器,它的宽度是400px,高度为200px。这个时候借助padding-top或者padding-bottom的值为50%。

根据容器的宽度和padding就可以计算出容器div的高度是200px。 

1.HTML结构

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>

详解:1.content里面必须包含一个子标签center

           2.所有其他内容放在子标签内,不能直接放在content中

2.CSS代码

 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%。(即,无论是上下的间距还是左右的间距都是用自身的值/父的宽度)

posted @ 2018-05-14 17:23  轩悦  阅读(2645)  评论(0编辑  收藏  举报