手写div垂直水平居中
div垂直水平居中分为两种情况:
宽高固定 和 不需要固定宽高
-
宽高固定
-
position + margin 负值的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-手写div水平垂直居中</title> <style> *{ padding: 0; margin: 0; } .box{ width: 200px; height: 200px; background-color: red; margin: 100px auto; /*主要代码*/ position: relative; } .item{ width: 100px; height: 100px; background-color: yellow; /*主要代码*/ position: absolute; left: 50%; top: 50%; margin: -50px; } </style> </head> <body> <div class="box"> <div class="item"> </div> </div> </body> </html>
实现思路:
/*1.给父级添加相对定位*/ position: relative; /*2.给子元素添加绝对定位*/ position: absolute; left: 50%; top: 50%; margin: -50px;
-
position + margin: auto
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-手写div水平垂直居中</title> <style> *{ padding: 0; margin: 0; } .box{ width: 200px; height: 200px; background-color: red; margin: 100px auto; position: relative; } .item{ width: 100px; height: 100px; background-color: yellow; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class="box"> <div class="item"> </div> </div> </body> </html>
实现思路:
/*1.给父级添加相对定位 */ position: relative; /*2.给子元素添加绝对定位*/ position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto;
-
display:table-cell + vertical-align: middle
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-手写div水平垂直居中</title> <style> *{ padding: 0; margin: 0; } .box{ width: 200px; height: 200px; background-color: red; display: table-cell; vertical-align: middle; } .item{ width: 100px; height: 100px; background-color: yellow; margin: auto; } </style> </head> <body> <div class="box"> <div class="item"> </div> </div> </body> </html>
实现思路:
/*1.给父级添加*/ dispaly: table-cell; vertical-align: middle; /*2.给子元素添加*/ margin: auto;
-
-
不需要固定宽高
-
position + transform
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-手写div水平垂直居中</title> <style> *{ padding: 0; margin: 0; } .box{ width: 400px; height: 400px; background-color: red; position: relative; } .item{ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); background-color: yellow; } </style> </head> <body> <div class="box"> <div class="item"> 树深时见鹿,溪午不闻钟. </div> </div> </body> </html>
实现思路:
/*1.给父级添加*/ position: relative; /*2.给子元素添加*/ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
-
dispaly: flex
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-手写div水平垂直居中</title> <style> *{ padding: 0; margin: 0; } .box{ width: 400px; height: 400px; background-color: red; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="box"> <div class="item" style="background-color: yellow;"> 树深时见鹿,溪午不闻钟. </div> </div> </body> </html>
实现思路:
/* -- 给父级添加 */ display: flex; align-item: center; justify-content: center;
-