2

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;
}
btmach
  • 375
  • 1
  • 7
  • 16
  • Possible duplicate http://stackoverflow.com/questions/15376634/how-can-i-center-a-div-within-another-div ? – Simon M. Jun 25 '15 at 15:13
  • Well the div .post-username should be flexible and setting a width to it may be a bad idea, since someone's username may be two characters while someone's is twelve? – btmach Jun 25 '15 at 15:15

2 Answers2

2
.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;
}
Usman Arshad
  • 868
  • 8
  • 19
1

.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>
Felix A J
  • 6,300
  • 2
  • 27
  • 46