Divs in a responsive grid-style layout with no vertical gap

余生长醉 提交于 2019-12-31 03:44:47

问题


I have a collection of divs (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:

  1. 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>
    
  2. 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>
    
  3. And this CSS

    .grid-item { width: 200px; }
    .grid-item--width2 { width: 400px; }
    
  4. 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
    });
    
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!