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();
});
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.
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.
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.
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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With