I have a child element in a parent container. I would like the child to be positioned from the center of the container, not from its top left corner. Here is a basic schema:

                                       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

How can I achieve this in pure css?

有帮助吗?

解决方案

You can't officially change the reference point of the positioning, but you can position at that centre point and then use margins to approximate your intent:

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

Simple JS Fiddle demo.

其他提示

There is no possibility in CSS to change the reference point from top or the bottom and left or right to another position. This is how CSS works.

The only possibility here is to work with additional margin, e.g.:

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

Just for fun, you could also do this with transforms:

<!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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top