2011-10-12 269 views
2

我在絕對定位一個相對定位的div圖像時遇到了問題。圖像應該在div中居中。爲此,我使用下面的CSS相對div內的絕對定位firefox

div 
{ 
    position: relative; 
    top: 0px; 
    left: 0px; 
} 
div img 
{ 
    margin-top: -10px; /*img width is 20px*/ 
    position: absolute; 
    top: 50%; 
} 

這對火狐之外的所有瀏覽器的偉大工程。 有沒有解決這個問題的方法?因爲我已經爲此搜尋了很多東西,所以我找不出什麼東西。 PS:不要跟我說使用行高。因爲圖片旁邊還有文字。所以這個選項對我不起作用。

回答

3

對於圖像你說top: 50%。什麼是50%?它應該是父元素的50%。什麼是父元素設置?如果沒有設置任何內容,問題就在於此。

+0

你在說什麼?這是div的父母的50%! – McTrafik

+0

@McTrafik - 是的,但該div沒有設置任何東西。所以沒有50%的參考,因此這個問題,50%是什麼? – Rob

1

爲什麼不這樣做

div 
{ 
    position: relative; 
    top: 0; 
    left: 0; 
} 
div img 
{ 
    position: relative; 
    top:25%; 
    left:50%; 
} 

relative的圖像是指從div50%的左側頂部25%

+0

我試過了,但'top:25%'什麼也沒做。左側正在工作,但我需要頂級定位 – Ozkan

+0

嘗試給'div'一個特定的高度。 I.E.圖片+填充/邊距的大小應該可以工作 – Biotox

0

如何自動邊距:

div img 
{ 
    margin-top: -10px; /*img with is 20px*/ 
    display: block; 
    position: relative; 
    margin-left: auto; 
    margin-right: auto; 
} 

這在Firefox的作​​品對我來說7

+0

您需要顯示:塊和位置:絕對值才能正常工作,但自動邊距對於居中事物很有用。 – tomtom

+0

水平邊距將起作用。但我需要垂直對齊圖像 – Ozkan

+0

也許我誤解了,但爲了垂直對齊圖像,您可以使用'margin-top:25%;'除上述之外。但是你必須手動設置數字 - auto似乎不起作用。 – tomtom

0

測試此:

div { 
    position: relative; 
    top: 0px; 
    left: 0px; 
    background: red; 
    width:500px; 
} 
div img { 
    margin-top: -10px; 
    //position: absolute; /*get it out*/ 
    display: block; /*Important*/ 
    margin: auto; /*Important*/ 
    top: 50%; 
} 
1

嘗試把它作爲背景圖片,如果你只是想形象那裏。

div 
    { 
     background-image: url('image.jpg'); 
     background-position: center; 
     background-repeat: no-repeat; 
     margin: 0px auto; 
     position: relative; 
     width: Xpx; 
     height: Xpx; 
     top: 0px; 
     left: 0px; 
     vertical-align: middle; 
    } 

併爲文本使用一個div裏面,並使用邊緣,填充或其他。