以绝对定位的div为中心

时间:2015-06-25 15:11:43

标签: html css

我需要将这个div包含在另一个div中:

Div居中:

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

它应该以此为中心:

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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>