问题
I want to layout a list of images in a grid format.
They shall behave like this:
- stretched to 100% of the screen width if viewed on small screens
- stretched to 50% of the screen width if viewed on tablet screens
- stretched to 25% of the screen width if viewed on large desktop screens
I have something very close, but the problem is, the images have different sizes, and therefore the layout is broken. How should I fix the code so that the smaller image will be stretched bigger to match the bigger boxes automatically?
See the problem here:http://jsfiddle.net/Gep2G/embedded/result/
My HTML source code:
<body>
<div id='wrapper'><img src='http://placekitten.com/352/288'/></div>
<div id='wrapper'><img src='http://placekitten.com/352/288'/></div>
<div id='wrapper'><img src='http://placekitten.com/352/288'/></div>
<div id='wrapper'><img src='http://placekitten.com/320/240'/></div>
<div id='wrapper'><img src='http://placekitten.com/320/240'/></div>
</body>
My CSS:
body {margin:0;padding:0}
img{width:100%;height:100%;}
#wrapper{width:100%;float: left;}
@media (min-width:320px) {
/* smartphones, iPhone, portrait 480x320 phones */
body {margin:0;padding:0}
img{width:100%;height:100%;}
#wrapper{width:100%;float: left;}
}
@media (min-width:961px) {
/* tablet, landscape iPad, lo-res laptops ands desktops */
body {margin:0;padding:0}
img{width:100%;height:100%;}
#wrapper{width:50%;float: left;}
}
@media (min-width:1025px) {
/* big landscape tablets, laptops, and desktops */
body {margin:0;padding:0}
img{width:100%;height:100%;}
#wrapper{width:50%;float: left;}
}
@media (min-width:1281px) {
/* hi-res laptops and desktops */
body {margin:0;padding:0}
img{width:100%;height:100%;}
#wrapper{width:25%;float: left;}
}
Editable code: http://jsfiddle.net/Gep2G/
回答1:
Its a simple fix.
http://jsfiddle.net/Gep2G/4/embedded/result/
img{width:100%; hieght:352px;}
As long as you specify only one dimension: the browser will auto fill the image in the correct proportion. Continue to set the height as desired for each media query.
Additionally there were a few errors in your css. For example an id should only be applied to a single element. Use classes for multiple elements ( like your wrapper element).
回答2:
i made a script to solve this issue before :
http://jsfiddle.net/prollygeek/QD9kZ/
side1=0,side2=0
$(".flexbox").children().each(function(index, element) {
if (index % 2 === 0) //odd children (starts with 0 )
{
$(this).css("top",side1+"px")
side1+=parseInt($(this).css("height"))
}
else //even children
{
$(this).css("top",side2+"px")
$(this).css("left","50%")
side2+=parseInt($(this).css("height"))
}
});
but if you want pure css solution i would recommend checking : http://designshack.net/articles/css/masonry/ the pure css solution.
回答3:
@media (min-width: 1281px){
#wrapper {
width: 25%;
float: left;
height: 20em;
}
}
来源:https://stackoverflow.com/questions/20486737/simple-css-grid-with-unequal-image-sizes