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.
遇到的问题
-
遇到一个图片窗的问题,在展示的时候经常会遇到展示图片列表的情况
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> -
图片之间间隔10px,首先很简单想到
css #readpic{} #readpic img{float:left;margin-left:10px;} -
完美啊,但是有一个问题,如果这个橱窗是在启示位置,则和整个页面右边有10px的距离,会对不齐。
-
如果用
margin-right:10px -
同意在右边会对不齐的情况。
-
翻了翻新浪图片的做法。解决思路是把最外框缩进10px解决,同样qq娱乐也是同样的解决的思路。
css #redpic{margin-left:-10px;} #readpic #readpic img{float:left;margin-left:10px;} -
看了taobao.com 则是用内距解决,这样似乎能使用于所有的情况了。
css #readpic{padding:10px} #readpic{margin:5px} -
还看到一种方法是用绝对定位,来源于qq主页。
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;} ... -
确实挺有意思。
-
大致如此。