1.垂直居中
a.使用 vertical-align:middle
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
display: table-cell;
vertical-align: middle;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>
b.让盒子移动50%,向后回退自己的一半
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
position: relative;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
position:absolute;
margin-top: 50%;
top:-150px;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>
c 使用 maring 计算盒子的上下距离让盒子居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>
2.水平居中
a.盒子水平线移动50%,向后退自身宽度的一半
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{
width: 500px;
height: 500px;
background: red;
/**盒子居中对齐**/
position: absolute;
/**第一种方式
left: 50%;
top:50%;
margin-left: -250px;
margin-top:-250px;*/
/**第二种*/
left: 50%;
top:50%;
transform: translate(-50%,-50%);//移动的距离以自身的宽度为准
}
</style>
</head>
<body>
<div></div>
</body>
</html>
b.使用margin:0 auto 居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>
c 测量最有边距 使用margin 移动
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
margin-left:100px;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>
d把盒子转成行内块 使用 text-align进行水平居中
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1{
width: 500px;
height: 500px;
border: 1px solid blue;
text-align: center;
}
.d2{
width: 300px;
height: 300px;
border: 1px solid red;
display: inline-block;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2"></div>
</div>
</body>
</html>