近期在复习前端,现在html css进行到form表单 即将进入js阶段:)
码码后想达到的效果大概如此
input text radio select textarea等
在html内给几个小标题用了同样的class
<form action="">
<div class="title">姓名</div>
<input type="text" >
<div class="title">昵称</div>
<input type="text" ><br><br>
<div class="title">性别</div>
<input type="radio" name="number" value="1" checked>男性
<input type="radio" name="number" value="2">女性
<div class="title">所在地</div>
<select name="local">
<option value="1">杭州</option>
<option value="2">宁波</option>
<option value="3">温州</option>
<option value="4">绍兴</option>
</select><br><br>
<div class="title">个人简介</div><br>
<textarea name="message" rows="10" cols="60" >介绍一下你自己吧</textarea><br><br>
</form>
想着通过nth child来制定个别的margin用以单独进行小修饰
section form .title {
font-size: 16px;
font-weight: 400;
margin-left: 40px;
line-height: 34px;
display: inline;
color: #333;
}
section form .title:nth-child(8) {
margin-left: 72px;
}
然后就出现了上图的样子
以下的代码并未生效
section form .title:nth-child(8) {
margin-left: 72px;
}
查阅nth-child用法文档之后发现
:nth-child(n) 指的是 选择父元素的第n个子元素 n大于0 从1开始
check以后觉得写的没问题- -,考虑是不是存在其他原因导致nth-child未起效
后来尝试后发现,nth-child在“兄弟混杂”的时候会存在失效的情况。
拿上面的举例子
我的form里面标签种类有div,input,select,textarea
所以当nth-child我指定为第八个的时候,我们以为他会正常从上往下数数到第八个
但是实际上他数到第二个的时候就懵逼了因为第一个是div,第二个是input,他们不同类
哇哦,这样我们可以得出一个沙雕结论——n=1的时候,nth-child永不失效(嚣张)
再来结合具体用法深入讲一下nth-child和nth-of-type的区别
form div:nth-child(2) {
margin-left: 72px;
}
这段代码的意思是通过form里的div寻找父元素并定位到它的第二个子元素
form div:nth-of-type(2) {
margin-left: 72px;
}
这段代码的意思是通过form里的div寻找父元素并定位到它的第二个div标签
nth-of-type可以用于兄弟姐妹混杂的情况,但是因为它认识所有类型,在查询时不需要计总数,计算该类型标签的个数即可
修改代码后生效
form div:nth-of-type(4) {
margin-left: 72px;
}