Align Image To The Center Both Vertically And Horizontally
I have a list of images which I need to align center both vertically and horizontally. How do I align the images in the center of the their respective li both horizontally and vert
Solution 1:
You don't need jQuery to do this cross-browser.
http://codepen.io/anon/pen/PZqdbV
All I did was add position relative to .snap and centered the images using position absolute.
* {
margin: 0;
padding: 0;
}
.clear_both {
display: block;
clear: both;
}
#main_content {
width: 850px;
margin: 0 auto;
}
#snap-list {
list-style-type: none;
width: 100%;
}
#snap-list.snap {
width: 202px;
height: 202px;
float: left;
margin: 5px;
outline: 1px solid lightgray;
position: relative;
}
#snap-list.snapimg {
max-width: 100%;
max-height: 100%;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
Solution 2:
If you really want to do this with jQuery, just loop over the list items, set their position to relative an then position the images accordingly, but it is really not necessary to do this with jQuery.
You will actually have to wait for each image to be fully loaded, otherwise you will not get the width
and height
of the image.
So it might be better to use a CSS solution just like relseanp suggested.
Here is an example.
var listItems = $('#snap-list').find('li');
$(window).load(function() {
listItems.each(function(i, item) {
var crntImg = $(item).find('img');
$(item).css('position', 'relative');
crntImg.css({
position: 'absolute',
top: ($(item).height() / 2) - (crntImg.height() / 2),
left: ($(item).width() / 2) - (crntImg.width() / 2)
});
})
});
* {
margin: 0;
padding: 0;
}
.clear_both {
display: block;
clear: both;
}
#main_content {
width: 850px;
margin: 0 auto;
}
#snap-list {
list-style-type: none;
width: 100%;
}
#snap-list.snap {
width: 202px;
height: 202px;
float: left;
margin: 5px;
outline: 1px solid lightgray;
}
#snap-list.snapimg {
max-width: 100%;
max-height: 100%;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><divid="main_content"><ulid="snap-list"><liclass="snap"><imgsrc="http://placehold.it/350x150"></li><liclass="snap"><imgsrc="http://placehold.it/250x350"></li><liclass="snap"><imgsrc="http://placehold.it/350x350"></li><liclass="snap"><imgsrc="http://placehold.it/350x450"></li><liclass="snap"><imgsrc="http://placehold.it/350x250"></li><spanclass="clear_both"></span></ul></div>
Post a Comment for "Align Image To The Center Both Vertically And Horizontally"