Ozkan
Ozkan

Reputation: 2041

absolute positioning within relative div firefox

I'm having trouble with absolute positioning an image in a relative positioned div. The image should be centered within the div. For this I use following 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. 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. Because there is also text next to the image. So this option will not work for me.

Upvotes: 2

Views: 6666

Answers (6)

Rob
Rob

Reputation: 15168

For the image you say top: 50%. 50% of what? It should be 50% of the parent element. What is the parent element set to? If it's not set to anything, therein lies the problem.

Upvotes: 3

aromerooca
aromerooca

Reputation: 39

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

Upvotes: 0

Scott Simpson
Scott Simpson

Reputation: 3850

This is a good article on the subject from CSS-Tricks:

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

Upvotes: 0

Klingstedt
Klingstedt

Reputation: 105

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.

Upvotes: 1

tomtom
tomtom

Reputation: 71

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

Upvotes: 0

Biotox
Biotox

Reputation: 1601

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.

Upvotes: 1

Related Questions