btmach
btmach

Reputation: 375

Centering an absolute positioned div

I need to center this div that is wrapped inside another div:

Div to be centered:

.post-username {
    padding: 10px;
    background: #000;
    border-radius: 4px;
    position: absolute;
    top: 0;
}

It should be centered inside of this:

.post {
    background: #3e4758;
    overflow: hidden;
    border-radius: 4px;
    width: 270px;
    height: 330px;
    position: relative;
}

Upvotes: 2

Views: 78

Answers (2)

Felix A J
Felix A J

Reputation: 6490

.post-username {
padding: 10px;
background: #000;
border-radius: 4px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.post {
background: #3e4758;
overflow: hidden;
border-radius: 4px;
width: 270px;
height: 330px;
position: relative;
}
<div class="post">
<div class="post-username">asdasd</div>

</div>

Upvotes: 1

Usman Arshad
Usman Arshad

Reputation: 868

.post-username {
    padding: 50px;
    background: #000;
    border-radius: 4px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
}

.post {
    background: #3e4758;
    overflow: hidden;
    border-radius: 4px;
    width: 270px;
    height: 330px;
    position: relative;
}

Upvotes: 2

Related Questions