一、水平居中:
1、div盒子水平居中:比较容易,直接设置div元素的margin: 0 auto就可以实现。
2、div里面的内容水平居中:text-align:center
二、垂直居中:
1、div盒子垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div居于页面正中间</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
background-color: #EAEAEA;
}
div{
width: 200px;
height: 200px;
background-color: #1E90FF;
}
.center-in-center{
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="center-in-center"></div>
</body>
</html>
2、div内容垂直居中:
三、水平垂直居中:div盒子和内容均水平垂直居中
<div class="parent"> <div class="child">DEMO</div> </div>
.parent{
width:200px;height:300px;
background:#ddd;
}
.child{
background:#666;
color:#fff;
}
1、方法一:设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中:
.parent {
position:relative;
}
.child {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
2、方法二 :定位+位移:使用子绝父相的定位方式,无须知道盒子自身的高度,使用范围较广:
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%; /* 父盒子宽度的50% */
top: 50%; /* 父盒子高度的50% */
transform: translate(-50%,-50%); /* 子盒子自身宽高的50% */
}
3、方法三:table-cell+inline-block:
将父盒子设置为table-cell(能够使元素呈单元格的样式显示),并设置text-align: center(使内容水平居中);vertical-align: middle(使内容垂直居中);。子盒子设置为inline-block可以使其内容变为文本格式,也可设置宽高:
.parent{
display: table-cell; /*使标签元素以表格单元格的形式呈现*/
text-align: center; /* 水平居中*/
vertical-align: middle; /* 垂直居中 */
}
.child{
display: inline-block; /* 将子盒子设置为行内块级(文本格式)*/
}
4、方法四:弹性盒子:
使用弹性盒子的时候需要给父级设置display:flex;在父元素上设置水平与垂直方向上的排列方式即可;
该方法不需要设置子元素:
.parent{
display: flex;
justify-content: center; /* 水平方向 居中*/
align-items: center; /* 垂直方向 居中*/
}
以上几种方式推荐使用弹性盒子,因为在使用定位的时候会使元素脱离文档流出现撑不起父盒子的问题,而在弹性盒子中不会出现这样的问题,而且利用弹性盒子还能解决其他的问题。