2016-11-17 19 views
0

我有一個容器div,其中高度和寬度都設置爲100%,位置是相對的。在div裏面,我使用display:block和margin:auto來對圖像進行居中(圖像比div小)。然後我試圖在圖像中使用position:absolute,left:45%,top 82px來居中文本。垂直對齊似乎沒問題,但隨着文本中字符的數量增加,文本不再在中間對齊。所以在下面的圖片中,如果文本是4個字符,文本將不再居中。有沒有更好的方法來動態調整文本?動態地在圖像中居中文本

enter image description here

HTML:

<div id="countup-container"> 
 
    <img id="countup-image" src="/_layouts/Images/abc/free.png" alt="Free">  
 
    <span id="ctl00" class="countup-text">101</span>  
 
</div>

相關CSS:

#countup-container { 
 
    height: 100%; 
 
    width: 100%; 
 
    position: relative; 
 
} 
 

 
#countup-image { 
 
    display: block; 
 
    margin: auto; 
 
    width: 300px; 
 
    height: 240px; 
 
} 
 

 
.countup-text { 
 
    z-index: 100; 
 
    position: absolute; 
 
    color: black; 
 
    font-size: 40px; 
 
    font-weight: bold; 
 
    left: 45.3%; 
 
    top: 82px; 
 
}

+5

請包括相關的代碼或小提琴。 –

+0

添加了相關代碼 – obautista

回答

3

如果您使用絕對定位居中你想改變你的left: 45%;left: 50%;然後設置一個轉換是這樣的:

.thing_to_center_horizontal { 
    top 82px; 
    left: 50%; 
    transform: translateX(-50%); 
} 

這將使它更具有動態內容的中心。

left: 50%;將根據內容的左上角將其放在中間位置,然後transform: translateX(-50%);會將內容寬度的50%(這是動態部分)移動到左側,使其居中。

有意義嗎?

但也許一個簡單的text-align: center;可能工作,但很難說,因爲你沒有發佈任何代碼。

+0

編輯原始文章以包含相關代碼。 – obautista

0

如果我瞭解你,你可以簡單地添加text-align:center到你的#countup-container

,並刪除left:45%.countup-text