div居中的三种方式
**1.**弹性布局(display:flex)
注:给需要居中的元素的父元素设置display: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>水平垂直居中</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box {
border:1px blue solid;
width: 600px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.box>div {
width: 400px;
height: 200px;
background-color: pink;
}
</style>
<body>
<div class="box">
<div>
123
</div>
</div>
</body>
</html>
**2.**绝对定位(position:absolute)
注:给要居中的元素加position:absolute属性,给要居中的元素的父元素加position:relative;
<!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>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box {
border: blue solid;
width: 600px;
height: 400px;
position: relative;
}
.box>div {
width: 400px;
height: 200px;
background-color: pink;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div class="box">
<div>
123
</div>
</div>
</body>
</html>
**3.**利用margin(外边距)来调整居中
计算需要居中元素在它父元素所剩的height/2就是margin-top的值
居中元素在它父元素所剩的width/2就是margin-left的值
<!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>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box {
border: blue solid;
width: 600px;
height: 400px;
}
.box>div {
width: 400px;
height: 200px;
background-color: pink;
margin: 100px 100px;
}
</style>
<body>
<div class="box">
<div>
123
</div>
</div>
</body>
</html>
上面三种方法都可实现如下所示的效果