我有以下html5正文:
<body>
<div id="container">
<div class="content" id="topleft">topleft</div>
<div class="content" id="topcenter">topcenter</div>
<div class="content" id="topright">topright</div>
<div class="content" id="centerleft">centerleft</div>
<div class="content" id="centercenter">centercenter</div>
<div class="content" id="centerright">centerright</div>
<div class="content" id="bottomleft">bottomleft</div>
<div class="content" id="bottomcenter">bottomcenter</div>
<div class="content" id="bottomright">bottomright</div>
</div>
</body>
我想实现一个看起来像这样的动态布局:
每个内容元素应该在相对于其父容器的角落中布置(停靠),并且所有中心元素应该在相应的侧面居中。父容器的大小或位置无关紧要,因此我无法使用绝对像素坐标进行定位。
这是我到目前为止所做的:
div#container {
background: lightblue;
position: relative;
width: 500px;
height: 500px;
}
div.content
{
width: 100px;
height: 100px;
position: absolute;
background: lightyellow;
text-align: center;
margin: auto;
}
div#topleft {
}
div#topcenter {
right: 50%; /*obviously doesn't center*/
}
div#topright {
right: 0px;
}
div#centerleft {
top: 50%; /*obviously doesn't center*/
left: 0px;
}
div#centercenter {
top: 50%; /*obviously doesn't center*/
right: 50%; /*obviously doesn't center*/
}
div#centerright {
right: 0px;
top: 50%; /*obviously doesn't center*/
}
div#bottomleft {
bottom: 0px;
}
div#bottomcenter {
bottom: 0px;
right: 50%; /*obviously doesn't center*/
}
div#bottomright {
right: 0px;
bottom: 0px;
}
这一切都适用于角落,但当然所有中心元素都没有对齐居中,我理解为什么。我只是不知道,这是怎么在CSS3中完成的......
答案 0 :(得分:1)
要在其父级中垂直居中固定高度元素,请使用:
top:50%;
margin-top:-50px;
对于水平,你可以左边和左边边做同样的事情,或者只是没有定义任何东西并使用“margin:0 auto”,因为它会自动向左和向右平均填充它们。