문제

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