日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

CSS未知宽高元素水平垂直居中

發布時間:2023/12/2 61 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CSS未知宽高元素水平垂直居中 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

方法一 :table、cell-table

思路:顯示設置父元素為:table,子元素為:cell-table,這樣就可以使用vertical-align: center,實現水平居中
優點:父元素(parent)可以動態的改變高度(table元素的特性)
缺點:IE8以下不支持

?

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>未知寬高元素水平垂直居中</title> </head> <style>.parent1{display: table;height:300px;width: 300px;background-color: #FD0C70; } .parent1 .child{display: table-cell;vertical-align: middle;text-align: center;color: #fff;font-size: 16px; }</style> <body><div class="parent1"><div class="child">hello world-1</div></div> </body> </html>

?

方法二:

思路:使用一個空標簽span設置他的vertical-align基準線為中間,并且讓他為inline-block,寬度為0
缺點:多了一個沒用的空標簽,display:inline-blockIE 6 7是不支持的(添加上:_zoom1;*display:inline)。
當然也可以使用偽元素來代替span標簽,不過IE支持也不好,但這是后話了

?

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>未知寬高元素水平垂直居中</title> </head> <style> .parent2{height:300px;width: 300px;text-align: center;background: #FD0C70; } .parent2 span{display: inline-block;;width: 0;height: 100%;vertical-align: middle;zoom: 1;/*BFC*/*display: inline; } .parent2 .child{display: inline-block;color: #fff;zoom: 1;/*BFC*/*display: inline; }</style> <body><div class="parent1"><div class="child">hello world-1</div></div><div class="parent2"><span></span><div class="child">hello world-2</div></div> </body> </html>

?

方法三:絕對定位

思路:子元素絕對定位,距離頂部 50%,左邊50%,然后使用css3 transform:translate(-50%; -50%)
優點:高大上,可以在webkit內核的瀏覽器中使用
缺點:不支持IE9以下不支持transform屬性

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>未知寬高元素水平垂直居中</title> </head> <style> .parent3{position: relative;height:300px;width: 300px;background: #FD0C70; } .parent3 .child{position: absolute;top: 50%;left: 50%;color: #fff;transform: translate(-50%, -50%); } </style> <body> <div class="parent3"><div class="child">hello world-3</div></div> </body> </html>

方法四:彈性盒子flex

思路:使用css3 flex布局
優點:簡單 快捷
缺點:兼容不好吧,詳情見:http://caniuse.com/#search=flex

?

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>未知寬高元素水平垂直居中</title> </head> <style> .parent4{display: flex;justify-content: center;align-items: center;width: 300px;height:300px;background: #FD0C70; } .parent4 .child{color:#fff; } </style> <body>div> <div class="parent4"><div class="child">hello world-4</div></div> </body> </html>

?

?

?

?


更多專業前端知識,請上 【猿2048】www.mk2048.com

總結

以上是生活随笔為你收集整理的CSS未知宽高元素水平垂直居中的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。