2016-02-13 35 views
1

我想將我的H2文字垂直放置在水平方向上,位於我的圖像上方。在圖像上方集中放置文字

有人可以解釋我是如何做到這一點的?

https://jsfiddle.net/q3odxfmb/

<div class="content"> 
 

 
<img src="http://placehold.it/940x510"> 
 
<h2> 
 
TEXT WILL GO HERE 
 
</h2> 
 

 
</div>

+1

這是一個更好的選擇https://jsfiddle.net/q3odxfmb/1/ @michaelmcgurk –

+0

當然是 - 讓綠色勾選後匆忙; - ) – michaelmcgurk

回答

2

小提琴https://jsfiddle.net/q3odxfmb/1/

img { 
    max-width: 100%; 
    vertical-align: middle; 
} 

#container { 
    position: relative; 
} 

#text-outer { 
    height: 100%; 
    margin-left: 12.5%; 
    position: absolute; 
    top: 0; 
    width: 75%; 
} 

#text-inner { 
    color: #fff; 
    position: absolute; 
    text-align: center; 
    top: 50%; 
    transform: translateY(-50%); 
    width: 100%; 
} 

這個問題已經問了這麼多次請參考以下鏈接

謝謝大家

Text Above Image CSS Z-Index Not Working

+0

非常感謝,Gautam Jha !!!有一個美好的一天:-) – michaelmcgurk

+1

高興地幫助你:) @michaelmcgurk –

0

設置文本作爲背景在一個div,和中央的文字在格。

HTML:

<div class="content"> 
    <h2 id="mytext"> 
    TEXT WILL GO HERE 
    </h2> 
</div> 

CSS:

div { 
    background: url("<image-link>") 
} 

#mytext { 
    line-height: 510px; 
    vertical-align:middle; 
    text-align: center; 
} 
+0

垂直對齊和線條高度都基本上做同樣的事情,在這裏。我會使用一個或另一個,最好是行高,因爲它不會影響div中的其他元素。更復雜的特性可以在複雜的頁面中實現更大的有限操作和靈活性 –

+1

除非行高設置爲div的高度,否則垂直對齊似乎不起作用。你可能會刪除垂直對齊,但你必須使用行高。 – cst1992

+1

是的。線路高度通常是在這些情況下要走的路!垂直對齊曾被用於很多!但是,如果確實知道父div中有單個子元素,它會更好。 –

1

這是很容易。只需設置CSS來:

.h2 { 
line-height:/*height of your image*/ 
} 

然後設置margin在div爲auto:

div { 
    background-url: <image-link>; 
    margin:auto 
} 

這應該完全居中。

您必須爲此方法設置一個小的餘量。

這裏是一個JSBin有一個簡單的方法,太: https://jsbin.com/vawowebolu/edit?html,css,js,output

+0

謝謝,賈斯汀 - 我現在就試試看。 – michaelmcgurk

+1

沒問題,我已經用JSBin更新了答案,以獲得另一種簡單的方法。 :) –