css设置盒子居中显示
第一种
-margin居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>实现盒子的绝对居中</title>
<style>
div{
width: 200px;
height: 200px;
background-color: pink;
/*使用定位*/
position: absolute;
/*偏移量*/
left: 50%;
top: 50%;
/*返回当前盒子一半的宽高像素值(外边距) - 负数*/
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
第二种
transform居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现盒子的绝对居中</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
/* border-radius: 50%; */
/*使用定位*/
position: absolute;
/*偏移量*/
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
第三种
flex居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 500px;
height: 500px;
margin: auto;
background-color: pink;
display: flex;
/* 水平居中 */
justify-content: space-around;
/* 垂直居中 */
align-items: center;
}
.content {
width: 70px;
height: 70px;
text-align: center;
line-height: 70px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="box">
<div class="content">内容</div>
</div>
</body>
</html>