我刚刚意识到以下两种方法都有效。我不确定我是否可以省略 label
并只放置 [type="checkbox"]
。
我很困惑,因为 documentation不同于教程和人们的代码。有些人使用元素,有些人忽略它们。
它起着重要的作用吗?这两个版本之间有什么区别吗?
如果有更有经验的人提供一些建议,我将不胜感激。
<form action="/submit-your-photo" id="your-photo">
<p>How would you describe yourself?</p>
<label><input type="checkbox" name="personality" checked> Loving</label>
<label><input type="checkbox" name="personality"> Lazy</label>
<label><input type="checkbox" name="personality"> Energetic</label><br>
<input type="text" placeholder="your photo URL" required>
<button type="submit">Submit</button>
</form>
CSS:
我的版本:
input[type="checkbox"]{
margin: 20px 10px;
}
二版:
[type="checkbox"]{
margin: 20px 10px;
}
最佳答案
第一个版本:
input[type="checkbox"]
... 以所有 input
元素为目标,这些元素具有 type
属性,其确切值为 checkbox
<支持>1.
第二个版本:
[type="checkbox"]
... 以所有具有 type
属性且确切值为 checkbox
1 的元素为目标。
与此相同:
*[type="checkbox"]
因为 checkbox
类型只对 input
元素 2 有效,所以这两个选择器实际上是相同的。第一个版本具有更高的特异性3。
在以下情况下,会有显着差异。
section[class="blue-background"]
[class="blue-background"]
在第一种情况下,只有具有该类值对的 section
元素才会获得蓝色背景。
在第二种情况下,具有该类值对的所有元素都获得蓝色背景。
1 https://www.w3.org/TR/css3-selectors/#selectors
2 https://www.w3.org/TR/2016/REC-html51-20161101/sec-forms.html#checkbox-state-typecheckbox
关于html - 如何以正确的方式使用 [attribute ="value"]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48392316/