簡體   English   中英

在固定位置Div垂直居中放置圖像

[英]Center an Image Vertically in a Fixed Position Div

SO上有很多關於垂直對齊的問題,但是我還沒有找到解決這個問題的明確答案。

我創建了一個小提琴以准確顯示我要執行的操作。

HTML:

<div id="fade"></div>
<div id="fullscreen">
    <img src="http://jira.seraphdevelopment.com/jmajewski/clean/uploads/pictures/n8jvxzd2476480d0.jpg" />
</div>

CSS:

#fade {
    /* Cover the entire viewport. */
    position: fixed;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;

    /* Transparent Background */
    background-color: #000;
    opacity: 0.50;
}

#fullscreen {
    /* Cover the entire viewport. */
    position: fixed;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

#fullscreen img {
    /* Adding the display: block allowed me to center
       the image horizontally with the margin: auto. */
    display: block;
    margin: auto;

    /* Limit the size of the image. */
    max-width: 80%;
    max-height: 80%;

    /* This didn't work for me. */
    vertical-align: middle;

    /* This didn't do anything, either. */
    line-height: 100%;
}

我正在嘗試制作各種燈箱,以便用戶單擊頁面上的圖像,從而使該圖像以全屏模式加載。 第一個div 淡入淡出將用於以半透明的黑色背景覆蓋整個頁面,從本質上給頁面帶來淡入淡出的效果,同時還使事物具有模態性。

我希望能夠將圖像嵌套在淺色 div ,但是遇到了一個問題。 在外部div上設置不透明度(以創建淡入淡出效果)會導致我的嵌套圖像繼承不透明度值。 因此,除了沒有背景,我添加了一個與第一個div相同的單獨的div ,並將圖像嵌套在其中。

作為記錄,我確實設法解決了不透明性問題,但是我尚未實現它。 感謝Blowski ,他是SO用戶,他發布了有關不透明性問題的答案:

我不想從CSS的父級繼承子級不透明度

長話短說,為了使圖像垂直居中,我已經嘗試了很多事情,但無濟於事。

請記住,此解決方案需要使用任何圖像!

我當然可以在$(window).resize()函數中添加一行代碼來手動居中圖像,但是如果可能的話,我想避免這樣做。 我很想學習解決此問題的方法,因為我似乎更經常遇到此類問題。

優點:為什么瀏覽器執行垂直對齊如此困難?

這是使用CSS將圖片固定在固定/絕對位置的div方法。

#fullscreen {
    /* Cover the entire viewport. */
    position: fixed;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

#fullscreen img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;

    /* Limit the size of the image. */
    max-width: 80%;
    max-height: 80%;
}

訣竅是為img使用position: absolute ,並將所有偏移設置為0,然后margin: auto將使圖像居中。

max-widthmax-height值將按預期工作。

這樣做的原因是圖像具有固有尺寸,因此CSS引擎具有特定的值來執行必要的數學運算,以使圖像在垂直和水平方向上居中。

參見演示: http : //jsfiddle.net/audetwebdesign/KG99S/

評論

請注意,此技術獨立於疊加層起作用。

同樣,無論圖像的縱橫比如何,此方法均有效。

參考

該技術源自CSS2規范,該規范涉及如何確定絕對定位的內聯替換元素的水平和垂直邊距。

http://www.w3.org/TR/CSS2/visudet.html#abs-replaced-width

http://www.w3.org/TR/CSS2/visudet.html#abs-replaced-height

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM