简体   繁体   English

相对div Firefox中的绝对定位

[英]absolute positioning within relative div firefox

I'm having trouble with absolute positioning an image in a relative positioned div. 我无法在相对定位的div中绝对定位图像。 The image should be centered within the div. 图像应位于div的中心。 For this I use following css 为此,我使用以下css

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

This works great on all browsers except Firefox. 这在除Firefox之外的所有浏览器上都很好用。 Is there any workaround for this? 有什么解决方法吗? Because i searched already a lot for this and i can't figure something out. 因为我已经为此进行了大量搜索,所以我无法弄清楚。

PS: Don't say to me to use line-height. PS:不要对我说使用行高。 Because there is also text next to the image. 因为图像旁边还有文本。 So this option will not work for me. 因此,此选项对我不起作用。

For the image you say top: 50% . 对于图像,您说top: 50% 50% of what? 50%是什么? It should be 50% of the parent element. 它应该是父元素的50%。 What is the parent element set to? 父元素设置为什么? If it's not set to anything, therein lies the problem. 如果未设置任何内容,那么问题就出在这里。

why not do something like this 为什么不做这样的事情

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

The relative for the image means 25% from the top of the div and 50% for the left side. 图像的relative值表示距div顶部的25% ,左侧的50%

Try putting it as a background image if you just want the image there. 如果只想在其中放置图像,请尝试将其作为背景图像。

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;
    }

and for the text use a div inside and position it using margin, padding or whatever. 对于文本,请在内部使用div并使用边距,填充或其他方式定位。

How about auto margins: 自动边距如何:

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

This works for me in firefox 7 这在Firefox 7中对我有用

Test this: 测试一下:

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%;
}

This is a good article on the subject from CSS-Tricks: 这是CSS-Tricks撰写的有关该主题的好文章:

http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/ http://css-tricks.com/snippets/css/absolute-center-vertical-horizo​​ntal-an-image/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM