How to center img within a div?

Asked

Viewed 1,438 times

5

I am making a grid of images (which will be links to the lightbox), I want 5 images per line, but they have different sizes, so I made the following html for each image:

 <div class="thumb">
<a href="images/900x600/img01.jpg" data-lightbox="gallery">
    <img src="images/thumbs/thumb01.jpg" alt="">
</a>
 </div>

And in CSS it went like this:

.thumb {
 width: 180px;
 height: 180px;
 position: relative;
 float: left;
}
.thumb img {
 position: relative;
 margin: auto;
 display: block;
}

To make everything right, the ideal would be for the images to be aligned both vertically and horizontally within their Ivs, which has 180px each, making them 5 images per line because my layout is 900px wide. For horizontal lines, I used margin: auto and display: block, but I can’t align vertically, I’ve tried to use vertical-align, put a span.helper, with 100% height and inline block, use line-height, but none of them work. And if I don’t use display: block in the imgs, they don’t align even horizontally. How do I center them?

EDIT: A detail that I didn’t mention, are 45 images, all with different sizes, so it is difficult to define in html or css the dimensions of each of them, because I believe it would considerably increase the size of the file or do not think?

  • Just set the image size in css, because if the image does not have the set size it cannot center and you will have to put the one that is the parent of the image with display block so that the image can be centered inside the a.

  • The problem is that there are 45 images, of varied sizes, I will have to define the size for each one of them?

  • The easiest way would be this, to put the size in home image, otherwise make a javascript, but would not advise, for css performance is better.

  • And it’s best to set the size in html itself or create a class for each image and define with css?

  • In this case it is better to put in html anyway.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.