一.单行文字居中: height: 100px;height: 100px;overflow: hidden;
二.多行内容居中(容器的高度不能固定): padding-top: 24px;padding-bottom: 24px;
三.块级实现垂直居中:
1.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body { position: relative; height: 100%; width: 100%; } #div1{ width: 200px; height: 200px; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: yellow; } </style> </head> <body> <div id="div1">千万千万请求请求请求</div> </body> </html>
通过position: absolute; top: 0; left: 0; bottom: 0; right: 0;实现居中,div的高度、宽度需要固定。
2.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body { position: relative; height: 100%; width: 100%; } #div1{ width: 200px; height: 200px; overflow: auto; margin: auto; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; background-color: yellow; } </style> </head> <body> <div id="div1">千万千万请求请求请求</div> </body> </html>
通过position: absolute; left: 50%;top: 50%;margin-left: -100px;margin-top: -100px;实现居中,div的高度、宽度需要固定
3.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body { height: 100%; width: 100%; position: relative; } #div1{ width: 200px; height: 200px; overflow: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); transform: translate(-50%,-50%); margin: auto; background-color: yellow; } </style> </head> <body> <div id="div1">千万千万请求请求请求</div> </body> </html>
通过transform属性实现居中,高度、宽度不需要固定。
4.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body { height: 100%; width: 100%; position: relative; display: table; } .table{ display: table-cell; vertical-align: middle; } #div1{ width: 200px; height: 200px; overflow: auto; margin: 0 auto; background-color: yellow; } </style> </head> <body> <div class="table"> <div id="div1"> 千万千万请求请求请求 </div> </div> </body> </html>
通过父元素设置为display: table;子元素设置为display: table-cell; vertical-align: middle;实现居中,div的高度、宽度不需要固定。
5.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body { height: 100%; width: 100%; display: box; display: -webkit-box; display: -ms-box; -webkit-box-pack: center; -ms-box-pack: center; box-pack: center; -webkit-box-align: center; -ms-box-align: center; box-align: center; } #div1{ width: 200px; height: 200px; background-color: yellow; } </style> </head> <body> <div id="div1"> 千万千万请求请求请求 </div> </body> </html>
通过flexbox的css3属性实现,display: box;box-pack: center;box-align: center;div的高度、宽度不需要固定。
时间: 2024-10-29 19:09:57