首页 > 开发 > CSS > 正文

CSS实现多行多列的布局的实例代码

2024-07-11 08:25:16
字体:
来源:转载
供稿:网友

1.两列多行:

 

HTML:

<div class="box1"> box1:实现两列多行布局 <ul> <li>111</li> <li>222</li> <li>333</li> </ul></div>

CSS:

.box1 { width: 500px; background: #EEEEEE;}.box1 ul { clear: both; overflow: hidden;}.box1 ul li { width: 48%; height: 100px; margin-bottom: 10px; background: skyblue; float: left;}.box1 ul li:nth-child(even) { margin-left: 4%;}

这用到了nth-child(),兼容ie9及以上的浏览器,中间的空隙就是两个并排div宽度之和,100%减去后剩下的宽度;

既然提到了nth-child(),那么就要说一下nth-of-type(),也是只兼容ie9及以上的浏览器。它与nth-child的区别是:

<div class="box"> <h1></h1> <h1></h1> <p></p> <p></p> <p></p></div>

如果要让第二个p标签背景为红色,那么,p:nth-child(4)这个能实现效果;而p:nth-of-type(2),就能实现。所以nth-of-type不管p标签前面有多少内容,都只认p的第二个元素。而nth-child却是找它父级的第几个元素。在这种情况下nth-of-type的优点就体现出来了。

2.多行多列

 

HTML:

<div class="box2"> box2:多行多列 <ul> <li> <div class="com"> 111 </div> </li> <li> <div class="com"> 222 </div> </li> <li> <div class="com"> 333 </div> </li> <li> <div class="com"> 444 </div> </li> </ul></div>

CSS:

.box2 { background: #EEEEEE; margin-top: 20px; width: 500px;}.box2 ul { overflow: hidden; margin-left: -10px; background: #EEEEEE;}.box2 ul li { width: 33.3333%; height: 50px; float: left; padding-left: 10px; box-sizing: border-box; margin-bottom: 10px;}.box2 ul li .com { height: inherit; background: skyblue;}

这里实现的原理是:子级使用padding-left(元素间的间隙)和box-sizing:border-box,父级使用margin-left负值,这个值和子级padding-left是一样的。li里面加div只是为了让效果明显,不然给li加上背景,由于

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表