2012-03-22 72 views
2

這裏是我的標記:垂直對齊,沒有高度知

<div id="container"> 
    <img id="image" src="image.jpg" /> 
    <div id="contents">Contents</div> 
</div> 

#container高度等於#image高度。 所有高度都是動態的(它們在窗口大小調整時發生變化)。 無法通過背景屬性設置圖像。

我怎樣纔能有圖像上的內容和垂直居中在#container

+0

爲什麼不能將圖像設置爲背景?你沒有得到它的工作,或有這種選擇的特定原因? – justanotherhobbyist 2012-03-22 12:59:02

+0

我確定通過設置背景圖像很容易做到這一點。然而,這是不可接受的 - 圖像是一個後縮略圖,在搜索引擎優化中相當重要 – Sergey 2012-03-22 16:43:33

+0

我假設高度不知道,寬度也不知道? – Andrew 2012-03-23 12:54:16

回答

1

這應該做你正在尋找。我剛剛在css中設置了容器和圖像的高度,但是如果它們在html中使用相同的設置或使用javascript,結果應該是相同的。背景顏色只是爲了清晰。

#container { 
background-color: #333; 
height: 200px; 
} 
#image{ 
height: 200px; 
float: left; 
} 
#contents{ 
line-height: 200px; 
float: left; 
position: fixed; 
} 

編輯:這是使用舊的經典保證金自動招解決方案的小提琴。這裏可能會導致問題的唯一原因是父母需要成爲職位:固定;這可能會在其他地方引發問題。主要的是它的工作原理,並沒有使用像素設置高度。

link

下面是從小提琴爲無定高度純的CSS溶液的代碼。

<div id="container"> 
    <img id="image" src="https://www.google.co.uk/logos/2012/juan_gris-2012-hp.jpg" /> 
    <div id="contents">Contents</div> 
</div> 

#container { 
    position: fixed; 
} 
#contents{ 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    width: 50%; 
    height: 10%; 
    margin: auto; 
} 
+1

來自OP「所有高度都是動態的(它們在窗口大小調整時發生變化)。「 – justanotherhobbyist 2012-03-22 12:56:56

+0

不可接受,如上所述,沒有高度是固定的 – Sergey 2012-03-22 16:50:57

+0

@SergeySedykh我編輯了這個,檢查出一個工作實現的小提琴 – Andrew 2012-03-23 13:36:47

1

#contents的高度是已知的嗎?在這種情況下,這應該這樣做(jsfiddle demo):

#container{ 
    position:relative; 

    /* For demo only */ 
    height:500px; 
    border: 5px solid red; 
} 
#image{ 
    position:absolute; 

    /* For demo only */ 
    height:500px; 
} 

#contents{ 
    position: absolute; 
    top:50%; 

    height:100px; 
    margin-top: -50px; /* Half of #contents height */ 

    /* For demo only */ 
    background-color: blue; 
} 
+1

從OP」所有的高度是動態的(他們改變窗口大小)「 – justanotherhobbyist 2012-03-22 12:56:46

+0

Ai,誤讀,雖然他只是指圖像和容器的高度 – Supr 2012-03-22 12:59:17

+0

不可接受,如上所述,沒有高度是固定的 – Sergey 2012-03-22 16:51:13

0

如果你知道#contents的高度,你可以設置

#container{position:relative;} 
#contents{ 
    position:absolute; 
    top:50%; /*50% of parent*/ 
    margin-top:/*negative one-half of container height i.e. if contaner is 4 em -2em* 
} 

你說你不知道的#contents的高度,雖然。

另一種選擇是將顯示器設置:以table-cell和使用vertical-align: middle

#container{ 
    display: table-cell; 
    vertical-align: middle; 
} 

但是這取決於你的瀏覽器是靶向的支持,可能會導致顯示問題爲好。

更確保消防方式是第一選擇一些jQuery的或javascript相結合,發現元素的高度並設置它的上邊距:

content= document.getElementById('content') 
content.style.marginTop = '-' + content.offsetHeight + 'px'; 

http://jsfiddle.net/h76sy/

編輯:對不起,在我的JavaScript中有一個錯誤,現在就試試吧

+0

關於JS解決方案 - 這是我現在與jQuery調整大小()組合使用。它在頁面加載時工作良好,並通過拖動窗口邊緣來調整大小,但是它在窗口最大化/恢復方面存在bug。 – Sergey 2012-03-22 17:08:05

+0

我認爲我必須更深入地研究'table-cell'解決方案 – Sergey 2012-03-22 17:09:09

+0

'table-cell'也不會工作:'table-cell'中有兩個對象,都是未知高度:圖像和div。 – Sergey 2012-03-22 18:21:01