说明
描述:之前有用过一些垂直居中的方法,今天在做小程序换装游戏的过程中,两个页面都需要用到垂直居中,为了选一个更方便的方法,我查阅资料学习并整理成本篇文章,方便自己随时查阅回顾。
小结
水平垂直居中
- flex 法
绝对定位法:
position:absolute;top:50%;left:50%;
- 已知元素宽高,则使用
margin-left:-(宽度/2),margin-top:-(高度/2)
。 - 不知元素宽高,可使用css3的:
transform:translate(-50%,-50%)
。
- 已知元素宽高,则使用
- css table 法
水平居中:
- 已知元素宽度:对块级元素设置宽度并使用
margin:auto
即可。 - 不知元素宽度:使用flex
1 通用法
使内容充满整个屏幕(高度、宽度100%),并使内容水平和竖直都居中【外层盒子不固定宽高】
<body>
<div class="box">
<image src="./img.png"></image>
<div>购物车竟然是空的</div>
<div>快去首页瞧瞧吧</div>
</div>
</body>
法1 【不需要确定外层盒子的高度(因为固定在可是区域了)】
.box {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 100%;
width: 100%;
display: flex;
flex-direction: row;
align-items: center;/*垂直居中*/
justify-content: center;/*水平居中*/
}
法2【需要确定外层盒子的高度】【更推荐!!!】
具体分析见文末的《微信小程序中使元素占满整个屏幕高度实现方法》
/* 在网页css中 */
html,body {
height:100%;
/* 或者 height:100vh */
};
/* 在小程序wxss中 */
page{
height:100%
}
.box {
height: 100%;
width: 100%;
display: flex;
flex-direction: row;/*主轴方向:行*/
justify-content: center;/*主轴居中*/
align-items: center;/*交叉轴居中*/
}
法3 table法【需要确定外层盒子的高度】
<div class="box">
<div class="do-middle">
<div class="do-middle-center">
<image src="./img.png"></image>
<div>购物车竟然是空的</div>
<div>快去首页瞧瞧吧</div>
</div>
</div>
</div>
条件1:使内容充满整个屏幕
html,body,.box{
height: 100%;
}
条件2:在某个小盒子里垂直居中
.box{
height: 300px;/* 或百分比均可 */
background: pink
}
公用部分
.do-middle {
display: table;
table-layout: fixed;
width: 100%;
height: 100%;
vertical-align: middle;
text-align: center;
}
.do-middle-center {
display: table-cell;
vertical-align: middle;
}
效果图
2 元素宽度、高度已知!
实现水平垂直居中就很简单了
<div class="box">垂直居中</div>
法1
.box{
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
background: pink;
}
法2
或者用margin: auto;
来实现水平垂直居中
.box{
width: 200px;
height: 200px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: pink;
}
3 当元素本身高度不确定
margin-left:-50%
是不行的,此时百分比不是元素本身的一半。
也就是说如果百分比是相对自身就可以了,那我们可以使用css3的transform
来代替margin
。
<div class="box">垂直居中</div>
.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
注意:transform目前浏览器兼容性不太好(手机web开发可忽略)。
4 微信小程序中使元素占满整个屏幕高度实现方法
在项目中经常要用到一个容器元素占满屏幕高度和宽度,然后再在这个容器元素里放置其他元素。
宽度很简单就是width:100%
,但是高度呢?我们知道的是height:100%
必须是在父元素的高度给定了的情况下才可以。
以前我的做法是用js获取屏幕的高度,然后将其赋值给height,屏幕高度在网页中为:window.innerHeight
;在微信小程序中则需要调用wx.getSystemInfo
接口,然后通过setData赋值。
但是显然通过js来进行的,效率上肯定不如css直接给定样式。
更好的方法
/* 在网页css中 */
html,body {
height:100%
};
/* 在小程序wxss中 */
page{
height:100%
}
将body和html设置为100%,这样我们就可以在他们的子元素中使用height:100%
来使的我们的容器元素占满屏幕的高度。
但是在微信小程序中,是没有dom对象的,但是我们看调试工具可以看到在dom树(我也不知道怎么叫了,就这么叫吧)中,根节点是page。*
禁止页面滚动
/* 在网页css中 */
html,body {
position: relative;
height: 100%;
overflow: hidden;
};
/* 在小程序wxss中 */
page{
position: relative;
height: 100%;
overflow: hidden;
}
/* 禁止页面滚动 */
.forbidden-scroll {
position: absolute;
top: 0;
left: 0;
height: 100%;
overflow: hidden;
}