我正在尝试将一个蓝色框完美地置于其父 div 的中心位置,并且我想确保以最简单的方式进行此操作。我必须做一些简单的数学运算才能知道设置蓝色框的宽度和高度的 px,只是想看看是否有更简单的方法。例如,要使 div 宽度居中,我可以执行“margin: auto”,是否有类似这样的高度?
这是 fiddle :http://jsfiddle.net/u2c64b52/
我的CSS代码如下:
#container {
width: 500px;
height: 500px;
background-color: lightgreen;
margin: 0 auto;
position: relative;
}
#box1 {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
right: 0;
}
#box2 {
width: 50px;
height: 50px;
background-color: blue;
margin: auto;
margin-top: 225px;
margin-left: 225px;
position: absolute;
}
最简单的方法? flex 盒子。不适用于 IE 10 或更低版本,并且我没有包含供应商前缀:
#outer {
background: red;
width: 400px;
height: 400px;
display: flex; /* These three lines make the magic happen */
justify-content: center;
align-items: center;
}
#inner {
width: 200px;
height: 200px;
background: blue;
}
<div id="outer">
<div id="inner">Lorem ipsum</div>
</div>
我是一名优秀的程序员,十分优秀!