1、问题如图:
代码如下:
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta charset="utf-8"/>
<script>
</script>
<style>
.father{
width:400px;
}
.c{
width:95px;
height:100px;
float:left;
border:1px solid black;
}
</style>
</head>
<body>
<div class="father">
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
</div>
</body>
</html>
2、解决方法
最终解决效果图如下:
具体方法:
2-1:使用伪类选择器(nth-child(4n+1))
代码如下:
<style>
.father{width:400px;}
.c{width:95px;height:100px;float:left;border:1px solid black;border-left:none;border-top:none;}
/*第一行加border-top*/
.father div:nth-child(1),.father div:nth-child(2),.father div:nth-child(3),.father div:nth-child(4){border-top:1px solid black;}
/*第一列加border-left*/
.father div:nth-child(4n+1){border-left:1px solid black;}
</style>
注意:4n+1可不能写成1+4n
2-2:思维决定意思形态,技巧处理
代码如下:
<style>
.father{
width:400px;
}
.c{
width:99px;/*此处有改动:(99+1)*4 = 400*/
height:100px;
float:left;
border:1px solid black;
border-left:none;
border-top:none;
}
/*给父元素加border-top和border-left*/
.father{
overflow:hidden;
border-top:1px solid black;
border-left:1px solid black;
}
</style>
注意:1、父元素.width = 子元素.widht*每行个数(才能不漏马脚)
2、由于里面子元素都为浮动,须给父元素设置overflow:hidden重拾高度;
2-2-2:扩展子元素浮动父元素失去告诉解决方法(clear:both)
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta charset="utf-8"/>
<script>
</script>
<style>
.father{
width:400px;
}
.c{
width:99px;/*此处有改动:(99+1)*4 = 400*/
height:100px;
float:left;
border:1px solid black;
border-left:none;
border-top:none;
}
/*给父元素加border-top和border-left*/
.father{
border-top:1px solid black;
border-left:1px solid black;
}
.clear{
clear:both;
}
</style>
</head>
<body>
<div class="father">
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="clear"></div>
</div>
</body>
</html>
2-2-3:上面解决浮动影响感觉不是很好,个人见解:家里小孩砸坏学校玻璃要家长赔礼道歉?
小孩如果犯错自己去解决不是更好?
优雅处理方案: :after伪类
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta charset="utf-8"/>
<script>
</script>
<style>
.father{
width:400px;
}
.c{
width:99px;/*此处有改动:(99+1)*4 = 400*/
height:100px;
float:left;
border:1px solid black;
border-left:none;
border-top:none;
}
.father:after{
display:block;
content:"clear";
height:0;
clear:both;
overflow:hidden;
visibility:hidden;
}
/*给父元素加border-top和border-left*/
.father{
border-top:1px solid black;
border-left:1px solid black;
}
</style>
</head>
<body>
<div class="father">
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
</div>
</body>
</html>