2017-06-15 64 views
0

我得到这个codepen,虽然它的工作完美,但我不明白为什么它不能将文本居中在包含框中间。以下是我的代码,它垂直居中,现在我想将它居中居中。水平居中绝对元素

.container-box p{ 
    position:absolute; 
    margin:auto; 
    height:40px; 
    background:grey; 
    color:white; 
    padding:10px; 
    box-sizing:border-box; 
    top: 0; left: 0; bottom: 0; right: 0; 
    display:table; 
    vertical-align:center; 
} 
+0

你必须根据'.container-box'的宽度来做。 '.container-box'的左边'.container-box'的50%。那会做。 –

+0

https://codepen.io/anon/pen/LLbENv检查:D –

回答

3

你需要给一个width属性为margin: auto(中心)工作。

.container-box p { 
    position:absolute; 
    width: 25%; //add this 
    margin:auto; 
    ... 
} 

此外另一个主要问题是,p是中心对准到所述容器(.container-box),而不是图像。 确保图像覆盖整个容器。你可以做到这一点的

.container-box img { 
    width: 100%; 
} 

现在它看起来像文本是在图像的中心,但在文字文本是在容器的中心,你的图像扩展到整个容器。

+0

'width'如何在这里工作,因为父元素/ img是未知的。 – Nofel

+0

图像不是这里的父母,'.container-box'是。因此,使图像覆盖整个div,然后它会看起来像文字在图像的中心 –

0
.container-box p{ 
    position:absolute; 
    margin:auto; 
    width: 200px; 
    ... 
} 

也宽100%的图像。

.container-box img{ 
    width: 100%; 
} 

入住这款改装版Codepen

1

您可以用定位做到这一点:

* {margin:0;box-sizing:border-box} 
 

 
.container-box { 
 
    display: inline-block; /* can also use inline-flex */ 
 
    position: relative; /* since one of the children is positioned absolute */ 
 
} 
 

 
.container-box > img { 
 
    display: block; /* removes bottom margin/whitespace */ 
 
    max-width: 100%; /* horizontal responsiveness */ 
 
    max-height: 100vh; /* vertical responsiveness */ 
 
} 
 

 
.container-box > p { 
 
    position: absolute; /* positioned relative to its parent */ 
 
    top: 50%; /* moved down by 50% of the parents height */ 
 
    left: 50%; /* moved right by 50% of the parents width */ 
 
    transform: translate(-50%,-50%); /* moved left and up by half of its width and height to achieve the perfect center */ 
 
    height: 40px; 
 
    background: Gray; 
 
    color: #fff; 
 
    padding: 10px; 
 
}
<div class="container-box"> 
 
    <img src="https://placeimg.com/640/480/any" alt=""> 
 
    <p>This is a temp. Image.</p> 
 
</div>

0

使用左起:50%以及顶部:50%。我清理了一点CSS

.container-box p{ 
    position:absolute; 
    height:40px; 
    background:grey; 
    color:white; 
    padding:10px; 
    box-sizing:border-box; 
    display:table; 
    left: 50%; 
    top: 50%; 
}