Jamie Bull
Jamie Bull

Reputation: 13529

Resizing images to fit a square using CSS

I have a collection of images which I am resizing to a set width, and allowing the height to be set automatically. All images are either square, or wider than they are tall and what I would like is to have a "letterbox/widescreen" effect for the non-square images. Is there a way to have the image centred vertically inside a square border using CSS?

Edited to add a very rough and ready layout. I'd also like the images to wrap, so that if the screen is zoomed in there may be only two on a row.

enter image description here

Upvotes: 0

Views: 967

Answers (3)

user3443238
user3443238

Reputation:

try vertical-align:middle; on all the images.

Upvotes: 2

Megaroeny
Megaroeny

Reputation: 827

If you have control over the actual images, meaning you have them yourself, the best solution IMO would be to crop them to be perfectly square. So if those images were 100px X 100px, you could add some padding:10px to give it some spacing between the edges and then your CSS border, for example:

div .image {
    background-image: url("images/blah.jpg");
    background-repeat: no-repeat;
    background-color: black;
    border: 3px solid black;
    padding: 10px;
}

I think that would accomplish exactly what you're wanting. :)

NOTE: If you don't have the images yourself, I would use the CSS properties: max-height or max-width. This will keep the images proportional at least. Don't use both, just one or the other.

Upvotes: 1

Sagi_Avinash_Varma
Sagi_Avinash_Varma

Reputation: 1509

u can use background-image instead of <img> inside the container <div> and set the CSS as

background:url("img_url") no-repeat ;
background-size:100% auto;
background-position:center center;
background-color:black;

This would give a widescreen effect for landscape images

Hope this helps!

Upvotes: 0

Related Questions