我想在另一个div里面居中一个div。
<div id="outerDiv">
<div id="innerDiv">
</div>
</div>
这是我目前使用的CSS。
#outerDiv {
width: 500px;
height: 500px;
position: relative;
}
#innerDiv {
width: 284px;
height: 290px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -147px;
margin-left: -144px;
}
如您所见,我现在使用的方法取决于#innerDiv的宽度和高度。如果宽度/高度改变,我将不得不修改margin-top和margin-left值。是否有任何通用的解决方案,我可以使用中心的#innerDiv独立于它的大小?
我发现使用margin: auto可以水平对齐#innerDiv到中间。但是垂直排列呢?
你可以在CSS中使用flex将div垂直和水平居中;
#outerDiv{
width: 500px;
height: 500px;
position:relative;
border:1px solid #000;
margin:0 auto;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
#innerDiv{
width: 284px;
height: 290px;
border:1px solid #eee;
}
第二个是这样的;
#outerDiv{
width: 500px;
height: 500px;
position:relative;
border:1px solid #000;
}
#innerDiv{
max-width: 300px;
height: 200px;
background-color: blue;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
border:1px solid #000;
border-radius:4px;
}
以及生成的HTML:
<div id="outerDiv">
<div id="innerDiv"></div>
</div>
你可以在CSS中使用flex将div垂直和水平居中;
#outerDiv{
width: 500px;
height: 500px;
position:relative;
border:1px solid #000;
margin:0 auto;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
#innerDiv{
width: 284px;
height: 290px;
border:1px solid #eee;
}
第二个是这样的;
#outerDiv{
width: 500px;
height: 500px;
position:relative;
border:1px solid #000;
}
#innerDiv{
max-width: 300px;
height: 200px;
background-color: blue;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
border:1px solid #000;
border-radius:4px;
}
以及生成的HTML:
<div id="outerDiv">
<div id="innerDiv"></div>
</div>
我想展示另一种跨浏览器的方法,可以使用CSS3 calc()解决这个问题。
我们可以使用calc()函数来控制子div的margin-top属性,当它的位置绝对相对于父div时。
使用calc()的主要优点是父元素的高度可以随时改变,并且子div将始终对齐到中间。
边缘顶部计算是动态的(通过css而不是通过脚本,这是一个非常大的优势)。
看看这个现场演示
<!DOCTYPE html>
<html>
<head>
<style>
#parent{
background-color:blue;
width: 500px;
height: 500px;
position:relative;
}
#child{
background-color:red;
width: 284px;
height: 250px;
position:absolute;
/* the middle of the parent(50%) minus half of the child (125px) will always
center vertically the child inside the parent */
margin-top: -moz-calc(50% - 125px);
/* WebKit */
margin-top: -webkit-calc(50% - 125px);
/* Opera */
margin-top: -o-calc(50% - 125px);
/* Standard */
margin-top: calc(50% - 125px);
}
</style>
</head>
<body>
<div id="parent">
<div id="child">
</div>
</div>
</body>
</html>
输出: