2017-06-15 65 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%; 
}