Westerfaq
Westerfaq

Reputation: 89

Position children from the center of their parent

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?

Upvotes: 0

Views: 47

Answers (3)

ralph.m
ralph.m

Reputation: 14365

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>

Upvotes: 0

David Thomas
David Thomas

Reputation: 253416

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.

Upvotes: 1

KittMedia
KittMedia

Reputation: 7466

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%;
}

Upvotes: 1

Related Questions