Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontally and vertically centered object doesn't work in Firefox?

I have an <img> which is centred horizontally and vertically, and it works in Chrome and Safari but unfortunately not in Firefox. In Firefox the <img> is centred horizontally but not vertically. How do I fix this? Does it have to do with the jquery animation?

You can see an example of my code here: http://jsfiddle.net/amagdk/kan94az0/

HTML

<img src="hover-kitty.png" alt="Hover Kitty">

CSS

img {
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

jQuery

$(document).ready(function(){
var hoverkitty = $("img");
   function hover() {
       hoverkitty.animate({top:'+=20'}, 1000);
       hoverkitty.animate({top:'-=20'}, 1000, hover);
   }
   hover();
});
like image 606
AnnaM Avatar asked Oct 15 '14 20:10

AnnaM


People also ask

How do you center a horizontally and vertically element?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you horizontally align an item Center?

Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do you set the center of an element vertically?

For example, if you're trying to align something horizontally OR vertically, it's not that difficult. You can just set text-align to center for an inline element, and margin: 0 auto would do it for a block-level element.

How do I horizontally center an image?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.


1 Answers

I create something that will work in firefox. You can use padding-top instead of top:

var hoverkitty = $("img");

function hover() {
    hoverkitty.animate({
        'padding-top': '+=20'
    }, 1000);
    hoverkitty.animate({
        'padding-top': '-=20'
    }, 1000, hover);
}

hover();
img {
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://itu.dk/people/akam/ta_challenge/hover-kitty.png" alt="Hover Kitty">
like image 155
Alex Char Avatar answered Oct 11 '22 18:10

Alex Char