Un1xCr3w Un1xCr3w - 3 months ago 22
CSS Question

Centering elements in absolutely-positioned parent

Unfortunately, I am unable to center the elements in the

position: absolute
parent.

Here is my code:



.cont-img {
width:400px;
position: relative;
}
.image {
width:400px;
height:400px;
background:black;
}
.desc {
position: absolute;
top:0px;
height:100%;
width:100%;
color:gold;
display:table;
}
.centered-items {
text-align:center;
display:table-cell;
vertical-align: middle;
}

<div class="cont-img">
<div class="image">

</div>
<div class="desc">
<div class="centered-items">
<div class="item1">
asdasd
</div>
<div class="item2">
asdasd
</div>
</div>
</div>
</div>





PS : I also tried the flex method but unfortunately it didn't work for me because the flex makes the elements not display.

All I need is to make the elements under this absolute parent centered vertically and horizontally.

Answer

CSS Positioning Method

For centering with absolute positioning it helps to use transform, in conjunction with the top and left offset properties. You don't need vertical-align or table properties.

.cont-img {
    width: 400px;
    position: relative;
}
.image {
    width: 400px;
    height: 400px;
    background: black;
}
.desc {
    position: absolute;
    top: 0;  
    height: 100%;
    width: 100%;
    color: gold;
}
.centered-items {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);     /* 1 */
}
<div class="cont-img">
    <div class="image"></div>
    <div class="desc">
        <div class="centered-items">
            <div class="item1">asdasd</div>
            <div class="item2">asdasd</div>
        </div>
    </div>
</div>

Notes:

  1. Here's an explanation of how this works: Element will not stay centered, especially when re-sizing screen

CSS Flexbox Method

For centering with flexbox, here's an example:

.cont-img {
    width: 400px;
    position: relative;
}
.image {
    width: 400px;
    height: 400px;
    background: black;
}
.desc {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: center;             /* 2 */
    align-items: center;                 /* 2 */
    height: 100%;
    width: 100%;
    color: gold;
}
<div class="cont-img">
    <div class="image"></div>
    <div class="desc">
        <div class="centered-items">
            <div class="item1">asdasd</div>
            <div class="item2">asdasd</div>
        </div>
    </div>
</div>

Notes:

  1. Here's an explanation of how this works: http://stackoverflow.com/a/33049198/3597276