相信在工做中常常會遇到須要某某元素垂直水平居中的需求,下面總結一下實現方法
絕對定位 + margin反向偏移
htmlhtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Sumon Test</title> <div style="background-color: yellow; width: 300px; height: 300px; position: relative; "> <div style="background-color: #F00; width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; margin: -50px 0 0 -50px; "> </div> </div> </head> <body> </body> </html>
絕對定位 + margin auto + 流體特性
html佈局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Sumon Test</title> <div style="background-color: yellow; width: 300px; height: 300px; position: relative; "> <div style="background-color: #F00; width: 100px; height: 100px; position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; "> </div> </div> </head> <body> </body> </html>
Tipsflex
當一個絕對定位元素,其對立定位方向屬性同時有具體定位數值的時候,流體特性就發生了。 具備流體特性絕對定位元素的margin:auto的填充規則和普通流體元素如出一轍: 1.若是一側定值,一側auto,auto爲剩餘空間大小; 2.若是兩側均是auto, 則平分剩餘空間;
絕對定位 + transform反向偏移
htmlspa
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Sumon Test</title> <div style="background-color: yellow; width: 300px; height: 300px; position: relative; "> <div style="background-color: #F00; width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); "> </div> </div> </head> <body> </body> </html>
flex佈局
htmlcode
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Sumon Test</title> <div style="background-color: yellow; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; "> <div style="background-color: #F00; width: 100px; height: 100px; "> </div> </div> </head> <body> </body> </html>
Tipsorm
1.justify-content 設置水平方向的元素位置 2.align-items 設置垂直方向的元素位置
table-cell佈局
htmlhtm
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Sumon Test</title> <div style="background-color: yellow; width: 300px; height: 300px; display: table-cell; vertical-align: middle; text-align: center; "> <div style="background-color: #F00; width: 100px; height: 100px; display: inline-block; "> </div> </div> </head> <body> </body> </html>
Tipsip
1.vertical-align 設置元素的垂直對齊方式 2.text-align 設置元素中的文本的水平對齊方式
以上就是我對CSS實現垂直水平居中的總結,若有異議歡迎評論留言。