H5 水平居中 水平垂直居中
Tips:元素一般分為 塊級元素 和 行內元素
塊級元素可以設置高度,寬度,行內元素則不能,如果將行內元素變成行內塊元素就可以設置寬高了,只需要將 display 屬性設置為 inline-block 即可;
一、 水平居中
? 1.行內元素水平居中:給行內元素的父級元素設置 text-align: center ;
<view style="text-align:center"><text>水平居中</text> </view>? 2.塊級元素水平居中:確保塊級元素有一個寬度,給行內元素設置 display: block ; 屬性,再給該元素設置 margin: 0 auto ;
<body><view style="width: 100%; height: 100%;"><text style="display: block; width: 50px; height: 50px; margin: 0 auto ;">水平居中</text></view> </body><!-- or --><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%) ;
<body style="position: relative;"><view style="position: absolute; left: 50%; transform: translateX(-50%);">水平居中</view> </body><!-- or --><body style="position: relative;"><view style="position: absolute; right: 50%; transform: translateX(50%);">水平居中</view> </body>? 4.使用 calc() 函數:看懂第3點方法,這第4點方法顯得有些雞肋了。這是在css3以前常見的方式。缺點很容易看出,寬度和減去的常量不能很好的動態變化;
<body style="position: relative;"><view style="position: absolute; width: 100px; left: calc(50% - 50px);">水平居中</view> </body><!-- or --><body style="position: relative;"><view style="position: absolute; width: 100px; right: calc(50% + 50px);">水平居中</view> </body>二、水平垂直居中
? 能夠理解上述水平居中,那么水平垂直居中就很容易理解,需要注意的就是如何垂直。
? 1.塊級元素水平垂直居中:給元素的父級元素設置具體高度 line-height 等于 height 高度
<view style="text-align: center; height: 100px; line-height:100px"><text>水平垂直居中</text> </view>? 2.相對與絕對定位水平垂直居中:再給子級元素設置 left: 50% ; top: 50% ; transform: translate(-50%,-50%) ;
<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 ;
<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 ;
常見,常用的水平居中,水平垂直居中的方法都在這了。當然還有很多其它的方法,感興趣話可以去研究研究。
有疑惑的小伙伴,可能是我表達不清楚,可以留言討論,如有錯誤,也希望大家不吝指出。
總結
以上是生活随笔為你收集整理的H5 水平居中 水平垂直居中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如果如果,如果没有如果
- 下一篇: CCFL、WLED、RGB LED背光液