如何水平垂直居中一个div
这里div指的是box,所有方法都是为了让box水平垂直居中
1.固定高宽(最简单的方法)
html如下:
<body>
<div id="box">box</div>
</body>
css如下:
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: red;
这里给box设置了宽和高,所以要在对应margin去掉一半(IE6以上可用)
效果如下:
2.有父元素且box高度固定
html代码如下:
<body>
<div class="father">
<div class="box">box</div>
</div>
</body>
css代码如下:
.father{
height: 500px;
position: relative;
border: solid 1px black;
}
.box{
height: 100px;
position: absolute;
left: 0;
top:0;
right:0;
bottom: 0;
margin:auto 0;
background-color: red;
}
这种方法与上面的类似主要利用绝对定位和margin实现垂直方向上的居中(IE8以上可用)
效果如下:
3.有父元素且box高度不固定
html代码如下:
<body>
<div class="father">
<div class="box">box</div>
</div>
</body>
css代码如下:
.father{
width: 500px;
height: 500px;
border: solid 1px black;
}
.box{
width: 100px;
position: relative;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
background-color: red;
}
把box向X和Y反方向转换50%(IE9以上可用)
效果如下:
4.弹性布局
html代码如下
<body>
<div class="father">
<div class="box">box</div>
</div>
</body>
css代码如下
.father{
width: 200px;
height: 300px;
border: solid 1px black;
display: -webkit-flex; /* Safari */
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
flex布局是改变子元素的布局,所以为box添加了一个father容器。
这里为了直观一点,我为father设置了宽高和边框,弹性布局中任何一个容器,行内元素都可以用flex布局,但是webkit内核的浏览器需要在flex前加-webkit-。
justify-content定义在主轴上排列方式,默认为水平方向(可以通过flex-direction改变),align-items定义在交叉轴上排列方式
效果如下:
5.table布局
html如下:
<body>
<div class="wrapper">
<div class="cell">
<div class="box">box</div>
</div>
</div>
</body>
css代码如下:
.wrapper{
width: 500px;
height: 500px;
border: solid 1px black;
display: table;
}
.cell{
display: table-cell;
vertical-align: middle;
}
.box{
width: 100px;
height: 100px;
margin-left: 200px;
background-color: red;
}
这种方法思路是竖直方向上居中比较难实现,先解决竖直居中,然后再水平居中,这里我用的是计算宽度,利用margin实现水平方向的居中
效果如下: