最近都在开发微信小程序,碰到一个这样的问题,就是图片在不同尺寸手机要求不被压缩(长宽之比不变),并且上下左右居中,效果图如下(左iPhone 7Plus,中iPhone 7,右iPhone X):
刚开始用px为单位,其实也可以,效果不是很好,于是改用vw(设备的宽度)和vh(设备的高度)了。
1vw=1%宽度,1vh=1%长度,下面是我在项目里面的代码:
demo.wxml:
<view class="tipPanel" style="display:{{display}}">
<image src="/images/close.png" class="close" bindtap='closeTip'></image>
<image src="/images/tip.png" class="tipImage"></image>
</view>
demo.wxss:(主要看.tipPanel .tipImage里面的)
.tipPanel{
box-sizing: border-box;
transition: 0.5s;
position: relative;
z-index: 2;
background: rgba(0,0,0,0.7);
width: 100vw;
height: 100vh;
}
.tipPanel .close{
position: absolute;
z-index: 4;
width: 8vw;
height: 8vw;
top: 50%;
right: 50%;
margin-top: -58vw;
margin-right: -40vw;
}
.tipPanel .tipImage{
position: absolute;
width: 84vw;
height: 120vw;
z-index: 3;
top:50%;
left: 50%;
margin-top: -60vw;
margin-left: -42vw;
}
比较巧妙,height和width都用vw作单位,这样就保持了比例不变。
居中的方法很多,针对我这个要求,先绝对定位(定位是定这个块左上角的那个点),上和左都50%,然后再左移自己宽度的一半和上移自己高度的一半,不懂意思的可以自己动手画一画。