這裏是我的標記:垂直對齊,沒有高度知
<div id="container">
<img id="image" src="image.jpg" />
<div id="contents">Contents</div>
</div>
的#container
高度等於#image
高度。 所有高度都是動態的(它們在窗口大小調整時發生變化)。 無法通過背景屬性設置圖像。
我怎樣纔能有圖像上的內容和垂直居中在#container
?
這裏是我的標記:垂直對齊,沒有高度知
<div id="container">
<img id="image" src="image.jpg" />
<div id="contents">Contents</div>
</div>
的#container
高度等於#image
高度。 所有高度都是動態的(它們在窗口大小調整時發生變化)。 無法通過背景屬性設置圖像。
我怎樣纔能有圖像上的內容和垂直居中在#container
?
這應該做你正在尋找。我剛剛在css中設置了容器和圖像的高度,但是如果它們在html中使用相同的設置或使用javascript,結果應該是相同的。背景顏色只是爲了清晰。
#container {
background-color: #333;
height: 200px;
}
#image{
height: 200px;
float: left;
}
#contents{
line-height: 200px;
float: left;
position: fixed;
}
編輯:這是使用舊的經典保證金自動招解決方案的小提琴。這裏可能會導致問題的唯一原因是父母需要成爲職位:固定;這可能會在其他地方引發問題。主要的是它的工作原理,並沒有使用像素設置高度。
下面是從小提琴爲無定高度純的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;
}
來自OP「所有高度都是動態的(它們在窗口大小調整時發生變化)。「 – justanotherhobbyist 2012-03-22 12:56:56
不可接受,如上所述,沒有高度是固定的 – Sergey 2012-03-22 16:50:57
@SergeySedykh我編輯了這個,檢查出一個工作實現的小提琴 – Andrew 2012-03-23 13:36:47
#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;
}
從OP」所有的高度是動態的(他們改變窗口大小)「 – justanotherhobbyist 2012-03-22 12:56:46
Ai,誤讀,雖然他只是指圖像和容器的高度 – Supr 2012-03-22 12:59:17
不可接受,如上所述,沒有高度是固定的 – Sergey 2012-03-22 16:51:13
如果你知道#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';
編輯:對不起,在我的JavaScript中有一個錯誤,現在就試試吧
爲什麼不能將圖像設置爲背景?你沒有得到它的工作,或有這種選擇的特定原因? – justanotherhobbyist 2012-03-22 12:59:02
我確定通過設置背景圖像很容易做到這一點。然而,這是不可接受的 - 圖像是一個後縮略圖,在搜索引擎優化中相當重要 – Sergey 2012-03-22 16:43:33
我假設高度不知道,寬度也不知道? – Andrew 2012-03-23 12:54:16