這裡整理兩個前端常見又實用的技巧:清除浮動,以及讓圖片在容器中水平垂直居中。
方法 1:
#test{clear:both;}
此處 #test 為浮動元素的下一個兄弟元素。
方法 2:
#test{display:block;zoom:1;overflow:hidden;}
此處 #test 為浮動元素的父元素;zoom:1 也可以替換為固定的 width 或 height。
方法 3:
#test{zoom:1;} #test:after{display:block;clear:both;visibility:hidden;height:0;content:'';}
此處 #test 同樣為浮動元素的父元素,透過偽元素在末尾插入一個清除浮動的看不見的方塊。
#test{display:table-cell;*display:block;*position:relative;width:200px;height:200px;text-align:center;vertical-align:middle;} #test p{*position:absolute;*top:50%;*left:50%;margin:0;} #test p img{*position:relative;*top:-50%;*left:-50%;vertical-align:middle;}
其中 #test 是 img 的祖父節點,p 是 img 的父節點。這段程式碼在現代瀏覽器中用 table-cell 加 vertical-align 實現居中,同時透過星號 hack 為 IE6/7 提供了 position 定位的變通方案。