源文章地址:http://webdesignerwall.com/tutorials/responsive-column-layouts
一般创建一个列布局,你需要给首尾列添加class来重置边缘距离并且清楚float状态。而我今天讲分享一个非常简单的CSS窍门,可以用 nth-of-type 伪装类来创建一个响应式的列布局。我在http://themify.me/themes就使用了这个方法,这个网页不用关心首尾class的状况,因为它的列的数目会根据视口宽度的不同进行相应的数目调整。换句话说,它可以响应式地显示为4列或3列或2列(Demo:http://webdesignerwall.com/demo/responsive-column-grid/)。
使用首尾class的不便
通常我们添加一个.first或.last class来清除表格边缘空白和浮动效果,这样做很无趣,而且很难处理为响应式的。
使用nth-of-type
使用nth-of-type(An+B)可以很方便地清除浮动效果和边缘空白,而不必添加.first和.last class,下面举个例子:
.grid4 .col:nth-of-type(4n+1)= 选择所有4列的元素,从第一个开始 .grid3 .col:nth-of-type(3n+1)= 选择所有3列的元素,从第一个开始 .grid2 .col:nth-of-type(2n+1)= 选择所有2列的元素,从第一个开始
.grid4 .col:nth-of-type(4n+1), .grid3 .col:nth-of-type(3n+1), .grid2 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; }
使它与媒体查询响应
使用百分比值代替像素值来使设计变得可响应。
/* col */ .col { background: #eee; float: left; margin-left: 3.2%; margin-bottom: 30px; } /* grid4 col */ .grid4 .col { width: 22.6%; } /* grid3 col */ .grid3 .col { width: 31.2%; } /* grid2 col */ .grid2 .col { width: 48.4%; }
将4列表格改为3列表格
当视口宽度小于740px时,讲4列表格展示位3列表格:
1.将.grid4 .col的宽度改为31.2% (1/3)
2.重置左边缘间距并且清除属性?
3.然后使用nth-of-type(3n+1)重新设置左边缘间距并且清除属性来建立一个3列表格
@media screen and (max-width: 740px) { .grid4 .col { width: 31.2%; } .grid4 .col:nth-of-type(4n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(3n+1) { margin-left: 0; clear: left; } }
讲4列和3列表格改为2列表格
当视口宽度小于600px时进行转换。使用技巧跟上面的差不多
@media screen and (max-width: 600px) { /* change grid4 to 2-column */ .grid4 .col { width: 48.4%; } .grid4 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } /* change grid3 to 2-column */ .grid3 .col { width: 48.4%; } .grid3 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid3 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } }
使所有类型的表格单列显示
(Demo:http://webdesignerwall.com/demo/responsive-column-grid/)
当视口宽度小于400px时
@media screen and (max-width: 400px) { .col { width: 100% !important; margin-left: 0 !important; clear: none !important; } }
IE问题
media请求和nth-of-type都不能被IE支持,需要使用selectivizr.js(http://selectivizr.com/)来使IE支持nth-of-type、使用respond.js(https://github.com/scottjehl/Respond)来使IE支持media
queries。糟糕的是,selectivizr.js和respond.js不能一起使用。所以在IE下,不能让列响应式在4~3~2列中转换。
译者博客:http://blog.csdn.net/wowkk