(1) 文本、图片等行内元素
<style>
.parent {
text-align: center;
}
</style>
<div class='parent'>
文本
</div>
<div class='parent'>
<img src=''>
</div>
(2) 定宽块级元素
<style>
.child {
width:800px;
margin: 0 auto;
}
</style>
<div class='child'>
</div>
(3) 不定宽块元素
方法1:设置内容为行内元素,同(1)
方法2:table + margin
<style>
.child {
display: table;
margin: 0 auto;
}
</style>
<div class='child'>
</div>
方法3:float + relative
<style>
.parent {
float: left;
position: relative;
left: 50%;
}
.child {
position: relative;
left: -50%;
}
</style>
方法4:absolute + transform
<style>
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
(4) 多个块级元素(单个块级元素也可用)
方法1:inline-block + text-align
<style>
.parent {
text-align: center;
}
.child {
display: inline-block;
*display: inline;
*zoom:1;
}
</style>
方法2:flex + justify-content
<style>
.parent {
display: flex;
}
.child {
justify-content: center;
}
</style>