- This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
Viewing 6 posts - 1 through 6 (of 6 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Absolute center an image issue
Hi Everyone,
I am currently working on a new website,
and i have some issues with my js code.
I would like to **center verticaly and horizontaly** an image inside a div.
I don’t know the size of the images (images will be retrieved from a json file)
Here is my js code : http://pastebin.com/NUhAdA7c
You can see the result here : http://emalsaifi.com/purprodv2/partenaires.php
The code sometime works, but when you reload the page,
the code doesn’t work, so my images are out of their div.
Can someone help me please ? :)
I’m sorry for my poor english,
Emal
The part of the JS where it sets the margin always sets it to 0. You can try to either set width and height on the img if that data is available in the JSON object, or wait till the image is loaded before running the script. Something like:
$(‘.partenaires’).find(‘img’).each(function() {
$(this).load(function() {
var $this = $(this),
widthImg = $this.width(),
heightImg = $this.height();
$this.css({
‘top’:’80px’,
‘left’: ‘160px’,
‘margin-left’:-widthImg/2,
‘margin-top’: -heightImg/2
});
});
});
EDIT: load is deprecated, something like `.bind(‘load’, function() { … });` would work though.
Actually, I think that doesn’t work right because I had to trigger the event to make it work here manually, but it’s worth a shot :)
you don’t need js at all. simply remove all the positioning and margins from the images, set the containing div to text-align: center (as you have), give a line-height equal to the height (160px) and keep the vertical-align: middle on the image.
That’s awesome :P
Indeed, easy, clever and awesome tricks !
Thank you very much Wolfcry911 and CrocoDillon !