2017-06-14 58 views
2

您好我没有得到正确的概念有关中心div在嵌套divs.Here是我的html。我想中心白色背景div。居中div与保证金:汽车不工作

<div class="div1"> 
    <div class="img"></div> 
</div> 
<div class="div2"> 

</div> 

和CSS

.div1{ 
    width :100%; 
    height: 300px; 
    background-color: black; 
    position: relative; 
} 
.img{ 
    width: 100px; 
    height: 100px; 
    position: absolute; 
    background-color : white; 
    display: block; 
    margin: auto; 
    bottom: 0%; 
    margin-bottom: -50px; 
    text-align: center; 

} 
.div2{ 
    width :100%; 
    height: 300px; 
    background-color: #e65100; 
} 

我尝试使用文本对齐到中心DIV:中心,但它不工作。 和输出是这里enter image description here

回答

3
.img { 
    ... 
    left: 0; 
    right: 0; 
} 

小提琴:https://jsfiddle.net/ep9co5g5/

+0

太神奇了!有用!感谢哥们,我会做出正确的答案。 –

2

您可以使用lefttranslateX,因为你正在使用的位置绝对使其居中,

你需要这个CSS添加到。 img

left:50%; 
transform:translateX(-50%); 

见代码片段:

.div1{ 
 
    width :100%; 
 
    height: 300px; 
 
    background-color: black; 
 
    position: relative; 
 
} 
 
.img{ 
 
    width: 100px; 
 
    height: 100px; 
 
    position: absolute; 
 
    background-color : white; 
 
    bottom: 0%; 
 
    margin-bottom: -50px; 
 
    left:50%; 
 
    transform:translateX(-50%); 
 

 
} 
 
.div2{ 
 
    width :100%; 
 
    height: 300px; 
 
    background-color: #e65100; 
 
}
<div class="div1"> 
 
    <div class="img"></div> 
 
</div> 
 
<div class="div2"> 
 

 
</div>

0

.div1{ 
 
    width :100%; 
 
    height: 300px; 
 
    background-color: black; 
 
    position: relative; 
 
} 
 
.img{ 
 
    width: 100px; 
 
    height: 100px; 
 
    position: absolute; 
 
    background-color : white; 
 
    display: block; 
 
    margin: auto; 
 
    bottom: 0%; 
 
    margin-bottom: -50px; 
 
    text-align: center; 
 
    left:0; 
 
    right:0; 
 

 
} 
 
.div2{ 
 
    width :100%; 
 
    height: 300px; 
 
    background-color: #e65100; 
 
}
<div class="div1"> 
 
    <div class="img"></div> 
 
</div> 
 
<div class="div2"> 
 

 
</div>