问题
I have a collection of div
s (cards). Each one will have a title, description, and image (all of varying lengths / sizes).
I want to display these "nicely" on screen.
By "nicely" I mean I want the image to be a thumbnail - horizontally centered after the title and description.
More importantly I want the card (containing div
) to be positioned one after the other (horizontally then vertically) and without any large vertical gaps.
Example:
I'm using Bootstrap's responsive column classes (col-lg
, col-md
, col-sm
) and img-responsive
. The main problem I'm hitting is the large vertical gaps.
Here's an attempt of mine.
Any CSS tricks to achieve a layout similar to my image above? (Only with fewer columns on smaller displays).
回答1:
The best way to achieve this layout is using Masonry
STEP by STEP:
you start by adding this:
<script src="/path/to/masonry.pkgd.min.js">`</script>
or using CDN
<script src="https://npmcdn.com/masonry-layout@4.0/dist/masonry.pkgd.js"></script> <!-- or --> <script src="https://npmcdn.com/masonry-layout@4.0/dist/masonry.pkgd.min.js"></script>
then this would be your HTML markup
<div class="grid"> <div class="grid-item">...</div> <div class="grid-item grid-item--width2">...</div> <div class="grid-item">...</div> ... </div>
And this CSS
.grid-item { width: 200px; } .grid-item--width2 { width: 400px; }
If you are using jQuery library , you can use it as a plugin and initialize it like this:
$('.grid').masonry({ // options itemSelector: '.grid-item', columnWidth: 200 });
otherwise you can initialize with vanilla JS like this:
var elem = document.querySelector('.grid'); var msnry = new Masonry( elem, { // options itemSelector: '.grid-item', columnWidth: 200 }); // element argument can be a selector string // for an individual element var msnry = new Masonry( '.grid', { // options });
PS- You can also initialize in HTML without any JS.
For further instructions, see Get Started here
Using CSS only, you can either use CSS Columns or CSS Flexbox. but it will lose in cross browser compatibility to the Masonry plugin
来源:https://stackoverflow.com/questions/37493780/divs-in-a-responsive-grid-style-layout-with-no-vertical-gap