1.页面居中absolute+transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面居中absolute+transform</title>
<style>
.parent
{
width: 300px;
height: 100px;
background: rgba(47, 67, 255, 0.26);
/******************注意一下关键代码**********************/
position: relative;
}
.child
{
width: 80px;
height: 100px;
background: rgba(225, 255, 43, 0.26);
/******************注意一下关键代码**********************/
/*优点:脱离文档流。不会对其他元素造成影响*/
/*ie6\7\8没办法兼容*/
position: absolute;
left:50%;
transform: translateX(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">MM</div>
</div>
</body>
</html>
2.页面居中flex+justify-content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面居中flex+justify-content</title>
<style>
.parent
{
width: 300px;
height: 100px;
background: rgba(47, 67, 255, 0.26);
display:flex;
justify-content: center;
}
.child
{
width: 80px;
height: 100px;
background: rgba(225, 255, 43, 0.26);
/*可以将justify-content: center; 替换为:margin:0 auto;*/
}
</style>
</head>
<body>
<div class="parent">
<div class="child">MM</div>
</div>
</body>
</html>
3.页面居中inline-block+text-align
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面居中inline-block+text-align</title>
<style>
.parent
{
width: 300px;
height: 100px;
background: rgba(47, 67, 255, 0.26);
/******************注意一下关键代码**********************/
text-align: center;
}
.child
{
width: 80px;
height: 100px;
background: rgba(225, 255, 43, 0.26);
/******************注意一下关键代码**********************/
/*可以通过别的方式兼容ie6、ie7*/
/* 缺点:.child会继承 .parent的text-align: center;*/
display: inline-block;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">MM</div>
</div>
</body>
</html>
4.页面居中table+margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面居中table+margin</title>
<style>
.parent
{
width: 300px;
height: 100px;
background: rgba(47, 67, 255, 0.26);
}
.child
{
width: 80px;
height: 100px;
background: rgba(225, 255, 43, 0.26);
/******************注意一下关键代码*********************/
/*ie 6、7要改变结构才能兼容*/
display: table;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">MM</div>
</div>
</body>
</html>