在移动端如何让宽度自适应来实现一个正方形,也就是宽度设置为百分比。javascript
使用javascript/jquerycss
<style>
.wrap {
width: 100%;
background: thistle;
} .child {
background: teal;
width: 20%;
} </style>
<body> <div class="wrap"> <div class="child">111</div> </div> </body> <script src="wjs/lib/jquery/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(window).on('resize', function () { $('child').css('height',$('li').css('width')); }).trigger('resize'); }) </script>
效果图:html
将元素垂直方向的一个padding,也就是padding-bottom或者padding-top设置为和宽度相同的百分比,将盒子撑起来,java
padding-bottom用法:jquery
可是padding是不包含盒子内容的,因此咱们把盒子高度设置为0,不然文字会溢出,致使高度大于宽度。this
能够看出来在正方形中有内容的时候,内容会在正方形外面,这是由于默认文字是从左到右,从上到下的排列因此paddin-bottom之后文字会在正方形上面spa
<style> .wrap {
width: 100%;
background: thistle;
} .child {
background: teal;
width: 20%;
padding-bottom: 20%;
height: 0;
} </style> <div class="wrap"> <div class="child"> 1111 </div> </div>
效果图:.net
padding-top用法:code
一样须要设置height:0,能够看出来在正方形中有内容的时候,内容会在正方形外面,这是由于默认文字是从左到右,从上到下的排列因此paddin-top之后文字会在正方形下方(外面)htm
<style> .wrap { width: 100%; background: thistle; } .child { background: teal; width: 40%; padding-top: 40%; height: 0; } </style> <div class="wrap"> <div class="child"> 1111 </div> </div>
效果图:
利用双层嵌套来写,将外层的div的position设置relative,内层的position设置为absoult,利用绝对定位消除空间占用
分别看设置成padding-top/padding-bottom的效果
padding-bottom:
<style> .wrap{ padding-bottom:50%; height: 0; background:thistle; width: 50%; position: relative; } .child{ position: absolute;
width: 100%; height: 100%; } </style> <div class="wrap"> <div class="child"> 111 </div> </div>
效果图:
padding-top:
<style> .wrap{ padding-top:50%; height: 0; background:thistle; width: 50%; position: relative; } .child{ position: absolute; width: 100%; height: 100%; } </style> <div class="wrap"> <div class="child"> 111 </div> </div>
效果图:
运行以后咱们发现写padding-top仍是不能够,咱们来检查代码发现,在写内层的div时候没有给top,left的值,让咱们把top,left加上再看看
.child{ position: absolute; width: 100%; height: 100%; left: 0; top: 0; }
效果图:
注:因此若是用padding-top的时候必定要记得添加top,left
使用 vw/vh 单位,可是须要注意的是vw/vh单位是将当前视口的宽度/高度平均分红100份的长度,并不是父级盒子,1vw = 1% viewport width。
<style> html,body { width: 100%; height: 100%; } .wrap { background: thistle; } .child { background: teal; width: 50%; height: 50vw; } </style> <body> <div class="wrap"> <div class="child"> 1111 </div> </div> </body>
效果图:
注意:此时,类名为wrap的div不设宽或将宽度设置100%;由于类名为child的div宽度咱们设置为百分比是相对父元素的。height咱们设置为了50vw,也就是50% viewport width。