1、使用绝对定位进行居中(已知元素宽高)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fade</title>
<style>
.out{
position:relative;
width: 200px;
height: 200px;
background-color: lightgreen;
}
.in{
position: absolute;
width: 100px;
height: 100px;
margin:auto;
top:0;
left:0;
right:0;
bottom: 0;
background-color: pink;
}
</style>
</head>
<body>
<div class="out">
<div class="in">测试内容</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fade</title>
<style>
.out{
position:relative;
width: 200px;
height: 200px;
background-color: lightgreen;
}
.in{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
background-color: pink;
}
</style>
</head>
<body>
<div class="out">
<div class="in">测试内容</div>
</div>
</body>
</html>
3、浮动元素的水平居中(不需要知道元素宽度高度)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fade</title>
<style>
.box{
width:200px;
height: 200px;
background-color: red;
}
.out{
float:left;
position:relative;
top: 50%;
left: 50%;
background-color: lightgreen;
}
.in{
position: relative;
top: -50%;
left: -50%;
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
<div class="out">
<div class="in">测试内容</div>
</div>
</div>
</body>
</html>