Tips:元素一般分为 块级元素 和 行内元素
块级元素可以设置高度,宽度,行内元素则不能,如果将行内元素变成行内块元素就可以设置宽高了,只需要将 display 属性设置为 inline-block 即可;
一、 水平居中
1.行内元素水平居中:给行内元素的父级元素设置 text-align: center ;
1 2 3
| <view style="text-align:center"> <text>水平居中</text> </view>
|
2.块级元素水平居中:确保块级元素有一个宽度,给行内元素设置 display: block ; 属性,再给该元素设置 margin: 0 auto ;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <body> <view style="width: 100%; height: 100%;"> <text style="display: block; width: 50px; height: 50px; margin: 0 auto ;"> 水平居中 </text> </view> </body>
<body> <view style="width: 100%; height: 100%;"> <view style="width: 50px; height: 50px; margin: 0 auto ;"> 水平居中 </view> </view> </body>
|
3.相对与绝对定位水平居中:确保父级元素具有相对定位属性 relative , 需要居中的子级元素具有绝对定位属性 absolute 。再给子级元素设置 left: 50% ; transform: translateX(-50%) ;
1 2 3 4 5 6 7 8 9 10 11 12 13
| <body style="position: relative;"> <view style="position: absolute; left: 50%; transform: translateX(-50%);"> 水平居中 </view> </body>
<body style="position: relative;"> <view style="position: absolute; right: 50%; transform: translateX(50%);"> 水平居中 </view> </body>
|
4.使用 calc() 函数:看懂第3点方法,这第4点方法显得有些鸡肋了。这是在css3以前常见的方式。缺点很容易看出,宽度和减去的常量不能很好的动态变化;
1 2 3 4 5 6 7 8 9 10 11 12 13
| <body style="position: relative;"> <view style="position: absolute; width: 100px; left: calc(50% - 50px);"> 水平居中 </view> </body>
<body style="position: relative;"> <view style="position: absolute; width: 100px; right: calc(50% + 50px);"> 水平居中 </view> </body>
|
二、水平垂直居中
能够理解上述水平居中,那么水平垂直居中就很容易理解,需要注意的就是如何垂直。
1.块级元素水平垂直居中:给元素的父级元素设置具体高度 line-height 等于 height 高度
1 2 3
| <view style="text-align: center; height: 100px; line-height:100px"> <text>水平垂直居中</text> </view>
|
2.相对与绝对定位水平垂直居中:再给子级元素设置 left: 50% ; top: 50% ; transform: translate(-50%,-50%) ;
1 2 3 4 5
| <body style="position: relative;"> <view style="position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);"> 水平垂直居中 </view> </body>
|
3. 固定定位中 left: 0 ; top: 0 ; right: 0 ; bottom: 0 : 确保元素有一固定宽高,再给元素设置一个 margin: auto ;
1 2 3 4 5
| <body> <view style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 100px; height: 100px"> 水平垂直居中 </view> </body>
|
4. flex 布局:最常见的一种布局方式,属性自由多变。给元素设置
display: flex ; align-items: center; justify-content: center ;
1 2 3 4 5
| <body> <view style="display: flex; align-items: center; justify-content: center;width: 200px; height: 200px"> 水平垂直居中 </view> </body>
|
常见,常用的水平居中,水平垂直居中的方法都在这了。当然还有很多其它的方法,感兴趣话可以去研究研究。