1.没有定位的盒子水平居中
1.让盒子的文字内容居中对齐: text-align: center
2.外边距实现盒子水平居中对齐,需要满足以下两个条件
*1.必须是块级元素*
*2.盒子必须指定了宽度*
width: 500px;
margin:0 auto; (上下为0,左右auto)
2.绝对定位的盒子居中对齐
水平居中
1.首先让盒子left:50%,走父盒子一半的大小
2.然后向左走自己盒子一半的大小,margin-left:负px。
垂直居中
1.首先让盒子top:50%,走父盒子一半的大小
2.然后向上走自己盒子一半的大小,margin-top: 负px。
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> div { text-align: center; width: 200px; height: 200px; background-color: red; position: absolute; /*水平居中*/ left: 50%; margin-left: -100px; /*这里是关键*/ /*垂直居中*/ top: 50%; margin-top: -100px; } </style> </head> <body> <div>div的文字</div> </body> </html>
也可以用transform实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> div { text-align: center; width: 200px; height: 200px; background-color: red; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); //或者 transform: translateX(-50%); transform: translateY(-50%); } </style> </head> <body> <div>div的文字</div> </body> </html>
3、flex实现居中对齐
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.main{
width: 500px;
height: 500px;
background-color: black;
display: flex;
/* 水平方向(主轴对齐) */
justify-content: center;
/* 垂直方向(交叉轴对齐) */
align-items: center;
}
.son{
width: 100px;
height: 100px;
background-color: #fff;
}
</style>
</head>
<body>
<div class="main">
<div class="son"></div>
</div>
</body>
</html>