html - 如何以正确的方式使用 [attribute ="value"]?

标签 html css css-selectors

我刚刚意识到以下两种方法都有效。我不确定我是否可以省略 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

3 https://stackoverflow.com/a/35657646/3597276

关于html - 如何以正确的方式使用 [attribute ="value"]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48392316/

相关文章:

javascript - 如何使maschek图像映射tinymce插件适用于tinymce 4

css - 如何在应用背景图像时保持现有按钮样式?

html - 使用 CSS { 空白 : nowrap } with Outlook

css - 负边距问题和不一致

javascript - 单击开关时如何在 2 个 div 之间平滑切换?

html - 为什么表单元素使我的 div 比没有它时占用更多空间?

asp.net - ASP/HTML/CSS - 不同于浏览器预览的设计 View

html - :focus pseudo-class and when it is applied

css - 无法应用第一个和最后一个子 CSS

html - 了解 CSS 选择器优先级/特异性