Reputation: 4811
I have different size images in my list items That are causing tiles to be pushed below in an odd way. What is the best way to have different size images (taller ones) fit in the container and have the container the same size and fluidly respond down? I have used a vw
as the height on the image which sets the tiles to be the same size, but causes the images themselves to squish, but is this the best way? uncomment the vw
in the example to see.
Code Pen: http://codepen.io/anon/pen/NNOWOZ
CSS:
ul{
overflow:hidden;
width:50%;
}
li{
list-style:none;
float:left;
margin:2% 1%;
border:1px solid black;
width:22%;
}
li img{
width:100%;
/*height:10vw;*/
}
Upvotes: 0
Views: 45
Reputation: 87833
As you have noticed, float:left
may not provide provide desirable results when the elements are different heights. In your example, they are all the same width, but various heights.
Since all your elements are percentage width, you know that no matter what the container size, there will only be 4 elements that fit on each row, so the following css solves your problem in this example
li:nth-child(4n+1) { clear: left; }
Other options which work better when the number of elements per row varies
Replacing float:left
with display:inline-block
will give you more of a clean wrap effect, but the images will then be bottom-aligned instead of top-aligned as they are now.
Fit them into squares, making your li
s to have the same width and height, and then place images inside with max-width: 100%; max-height: 100%
. This will force a certain height thereby solving the float
problem.
You may prefer to use background-image
, with background-size: cover
if you would like the images cropped into a square as many smartphone gallery apps would do. This doesn't work well for all use cases. Also background images won't print by default.
If you go this route, you can center the image vertically as well.
Use JavaScript which gives you unlimited flexibility but requires more work.
Upvotes: 2