Legacy Archive (2014): Originally written in Chinese on doubixie.com and translated into English for this edition. All archive posts · Home

CSS Notes: Image Grid Spacing & Alignment

Original Chinese title: css笔记

The Problem

  • I ran into an image-grid layout issue that comes up often when displaying a list of thumbnails:

    html
    <div class="readpic">
        <ul class="clearfix">
            <li><a href=""><img src="1.jpg"></a></li>
            <li><a href=""><img src="1.jpg"></a></li>
            <li><a href=""><img src="1.jpg"></a></li>
            <li><a href=""><img src="1.jpg"></a></li>
        </ul>
    </div>
  • To put a 10px gap between images, the first intuitive thing to try is:

    css
    #readpic{}
    #readpic img{float:left;margin-left:10px;}
  • Looks great—except there’s a catch: if this grid starts flush at the edge, the extra 10px leaves a gap on one side and throws off the alignment with the rest of the page.

  • If you use

    margin-right:10px
  • You similarly end up misaligned on the right edge.

  • I checked how Sina Pictures handles this: their trick is to pull the outer container back by 10px with a negative margin. QQ Entertainment uses the exact same approach:

    css
    #redpic{margin-left:-10px;}
    #readpic
    #readpic img{float:left;margin-left:10px;}
  • Looking at taobao.com, they solve it using padding instead, which seems to work across all cases:

    css
    #readpic{padding:10px}
    #readpic{margin:5px}
  • I also saw another method using absolute positioning, from the QQ homepage:

    html
    <div class="readpic">
            <a href="" class="picItem pic1"><img src="1.jpg"></a>
            <a href="" class="picItem pic2"><img src="1.jpg"></a>
            <a href="" class="picItem pic3"><img src="1.jpg"></a>
            <a href="" class="picItem pic4"><img src="1.jpg"></a>
    </div>
    css
    #readpic{}
    #picItem{position:absolute;overflow:hidden}
    #pic1{left:0;top:0;}
    ...
  • Pretty neat.

  • That’s about it.