2011-10-12 178 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里面,并使用边缘,填充或其他。