将孩子放在父母的中心

时间:2014-04-18 22:40:51

标签: html css position

我在父容器中有一个子元素。我希望孩子从容器的中心定位,而不是从左上角定位。这是一个基本架构:

                                       x x x x x x x x x x x x x x x x x x x
.parent                                x                                   x
{                                      x                                   x
    position: absolute;                x                                   x
}                                      x                                   x
                                       x                                   x
.child                                 x                 .                 x
{                                      x                 |                 x
    position: absolute;                x       top: 50px |                 x
    top: 50px;                         x                 v----->x x x      x
    left: 50px;                        x            left: 50px  x   x      x
}                                      x                        x x x      x
                                       x                                   x
                                       x x x x x x x x x x x x x x x x x x x

如何在纯CSS中实现这一目标?

3 个答案:

答案 0 :(得分:1)

CSS不可能将参考点从顶部或底部,左侧或右侧更改为另一个位置。这就是CSS的工作原理。

此处唯一的可能性是使用其他margin,例如:

.child {
    left: 50%;
    margin: 50px 0 0 50px;
    position: absolute;
    top: 50%;
}

答案 1 :(得分:1)

您无法正式更改定位的参考点,但可以定位在该中心点,然后使用margin来估算您的意图:

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: 50px;
    margin-left: 50px;
}

Simple JS Fiddle demo

答案 2 :(得分:0)

只是为了好玩,你也可以用变换来做到这一点:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>

.parent {
    width: 100%;
    height: 500px;
    background-color: #ffa;
    position: absolute;
    width: 500px;
    height: 400px;
    background: #e7e7e7;
}

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(50px, 50px);
    transform: translate(50px, 50px);
    height: 2em;
    width: 2em;
    background-color: #000;
}
</style>
</head>
<body>

<div class="parent">
    <div class="child"></div>
</div>

</body>
</html>
相关问题