1 水平居中。给DIV一个宽度,设置maigin:0 auto;
div{
width:200px;
margin:0 auto;
}
2 绝对定位的div水平垂直居中
.parent{
position:relative;
}
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /* 方便看效果 */
}
3 水平垂直居中一
.parent{
position:relative;
}
div{
position:absolute;
width:600px;
height:400px;
top:50%;
left:50%;
margin:-200px 0 0 -300px;
background-color:red; /* 方便观看 */
}
4 水平垂直居中二,未知容器宽高。
transform中的平移方法translate(X方向,Y方向)
.parent{
position:relative;
}
div{
position:absolute;
width:XXXpx;
height:XXXpx;
top:50%;
left:50%;
transform:translate(-50%,-50%);
background-color:red; /* 方便观看 */
}
5 水平垂直居中三
使用flex布局 实际使用时应考虑兼容性。Webkit内核的浏览器,必须加上-webkit前缀。
注意,设为Flex布局以后,子元素的float、clear和vertical-align属性将失效。
.container {
display: flex;
align-items: center; /* 垂直居中 align-items属性定义项目在交叉(Y)轴上如何对齐 */
justify-content: center; /* 水平居中 justify-content属性定义了项目在主(X)轴上的对齐方式 */
}
.container div {
width: 100px;
height: 100px;
background-color: pink; /* 方便看效果 */
}
注:行内元素居中 , 直接使用 text-align:center;即可。
使用flexbox实现三等分,左右两边分别贴在左边和右边。
<style type="text/css">
body{
margin: 0;
padding: 0;
}
.container {
height: 600px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.container div {
height: 200px;
width: 200px;
/* flex: 1; //不用宽度时候可以直接三等分*/
}
.left{
background-color: red;
}
.right{
background-color: pink;
}
.content{
background-color: blue;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="content"></div>
<div class="right"></div>
</div>
</body>