为什么我的叠加div不是居中的

时间:2014-09-28 20:49:58

标签: css

我确信这对专业人士来说是“简单的”:

我迷失了如何将叠加居中(水平和垂直)到其父级。有关详细信息,请参阅jsfiddle链接。

提前感谢您的时间......

LB

<div class="grandparent">
    <div class="parent">
        <!-- 1st row */ -->
        <div class="child">1-1</div>
        <div class="child">1-2</div>
        <div class="child">1-3</div>

        <!-- 2nd row */ -->
        <div class="child">2-1</div>
        <div class="child">2-2</div>
        <div class="child">2-3</div>

        <!-- 3rd row */ -->
        <div class="child">3-1</div>
        <div class="child">3-2</div>
        <div class="child">3-3</div>


        <div class="overlay">
            Overlaysdfds 
            line2sdf sdfdsf sdfsdf sfdsdf
            <P />line 3
         </div> 

    </div>


</div>   

和CSS:

<style>
.grandparent {
    posttion: relative;
    height: 100%;
    width:100%;
    max-width:600px;

    margin: 0 auto;
    text-align:center;
    border: 1px solid green;
    overflow: hidden;
}

.parent {
    width: 75%;
    height: 75%;
    margin: auto;
    border: 1px solid blue;
    text-align: center;
    padding:20px;
    verflow:hidden;
}
.parent:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}
.child {
    posttion: relative;
    float:left;
    width: 30%;
    padding-bottom: 22%; 
    margin:1.66%;
    background-color: #1E1E1E;
    color: #ffffff;
}

.overlay {
    position:absolute;
    top:50%;
    left:50%;
    margin-left: -150px;
    margin-top:-100px;
    color: white; background: #666666; opacity: .8;
    z-index: 1000;
}
<style>

以下是示例

的链接
http://jsfiddle.net/lb6688/aj7udvsq/3/

再次,感谢你的时间!

2 个答案:

答案 0 :(得分:4)

使用transform:translate(-50%, -50%)将元素置于父元素的中心(而不是margin-top和margin-left的硬编码值):

.overlay {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
    color: white; background: #666666; opacity: .8;
    z-index: 1000;
}

在此处查看:http://jsfiddle.net/aj7udvsq/4/

答案 1 :(得分:0)

查看CSS的更改:http://jsfiddle.net/csdtesting/w4boh5mg/1/

.overlay {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);    
    max-width: 50%;
    text-align: center;
    border: 1px solid blue;
    color: white; background: #666666; opacity: .8;
}

  .parent {
    position: relative; /* or absolute */
    margin: 5%;
    width: 80%;
    height: 500px;
    border: 1px solid red;
}