方式一
重点:text-align
要求子元素:inline 或 inline-block
优缺点:兼容性好。缺点是属性会继承,如果子元素有子元素自动继承居中属性需要挨个单独写text-align属性
.father{
text-align: center;
}
.child{
width: 200px;
height: 200px;
background: red;
display: inline-block;
}
方式二
重点:margin
要求子元素:不能为inline
优缺点:只需要对子元素单独设置即可实现居中。缺点是子元素不能脱离文档流,如果脱离,则margin失效
.father{
background: gray;
}
.child{
width: 200px;
height: 200px;
background: red;
display: table;
margin: 0 auto;
}
方式三
重点:子绝父相,transform
优缺点:不论父级标签是否脱离了文档流,对子级标签都不会影响水平居中效果。缺点是transform是CSS3新增属性,浏览器兼容性不好
.father{
width: 500px;
height: 200px;
position: relative;
background: #000;
}
.child{
background: green;
width: 200px;
height: 200px;
position: absolute;
left: 50%;
transform: translateX(-50%);
}