参考:
CSS常见布局及解决方案
把简单做好也不简单-css水平垂直居中
文字水平居中
对于单行文字来说,直接使用text-align: center即可。
多行文字可以看作一个块级元素参考margin法和定位法。
1、margin法:子节点:margin + 定宽
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
}
.child {
background-color: #fe6464;
width: 100px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
需要满足三个条件:
1.元素定宽
2.元素为块级元素或行内元素设置display:block
3.元素的margin-left和margin-right都必须设置为auto
三个条件缺一不可。
效果图:
2、子节点:table + margin
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
}
.child {
background-color: #fe6464;
display: table;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
display: table 在表现上类似 block 元素,但是宽度为内容宽。
无需设置父元素样式 (支持 IE 8 及其以上版本)兼容 IE 8 一下版本需要调整为 table
优点:只需要对自身进行设置
不足:IE6,7需要调整结构
效果图:
3、子节点:inline-block + 父节点:text-align
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
text-align: center;
}
.child {
background-color: #fe6464;
display: inline-block;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
兼容性佳(甚至可以兼容 IE 6 和 IE 7)
优点:兼容性好; 不足:需要同时设置子元素和父元素
效果图:
4、定位法:父节点:relative + 子节点:absolute + margin-left
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
position: relative;
}
.child {
background-color: #fe6464;
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
1.元素定宽
2.元素绝对定位,并设置left:50%
3.元素负左边距margin-left为宽度的一半
子节点宽度需要固定
相比于使用transform ,有兼容性更好
效果图:
5. 定位法:父节点:relative + 子节点:absolute + transform
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
position: relative;
}
.child {
background-color: #fe6464;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
绝对定位脱离文档流,不会对后续元素的布局造成影响。
transform 为 CSS3 属性,有兼容性问题
不足:兼容性差,IE9及以上可用
子节点:不设置width具体值
position: absolute;
left: 50%;
-webkit-transform: translate(-50%,0);
-ms-transform: translate(-50%,0);
-o-transform: translate(-50%,0);
transform: translate(-50%,0);
效果图:
6. 父节点:flex + justify-content
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
}
.child {
background-color: #fe6464;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
只需设置父节点属性,无需设置子元素
flex有兼容性问题,缺点:兼容性差,如果进行大面积的布局可能会影响效率.
效果图: