html - 第一个元素的 CSS 选择器不是 sibling

标签 html css css-selectors

我想知道这是否可能。使用此 html:

<h1></h1>
<form>
    <label><input type="text"></label>
    <label><input type="text"></label>
    <label><input type="text"></label>
</form>

我知道我能做到:

label:first-child{}

但我想知道是否可以只选择前面有 h1 的第一个标签,该标签与 + 或 ~ 或其他内容不在同一级别。

最佳答案

您可以使用以下选择器:

h1 + form > label:first-child {
   /* some properties here */
}

所以上面的选择器将选择 form 元素,它是 h1 的兄弟元素,然后它进入并选择第一个直接 label元素,因此我正在使用 >

如果您确定您的 form 元素中可能没有任何进一步嵌套的 label 元素,您可以安全地删除 > .


请注意,这是一个非常通用的标签选择器,我建议您将元素包装在一个包装器元素中并给它一个 classform-wrapper 并修改你的选择器喜欢

.form-wrapper h1 + form > label:first-child {
  /* some stuff */
}

关于html - 第一个元素的 CSS 选择器不是 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337141/

相关文章:

javascript - 使用javascript保存div内容的HTML按钮

html - 将鼠标悬停在菜单和子菜单上

javascript - meteor 显微镜激活光标

javascript - iphone/ios 中心的按钮文本

jquery - (jQuery)基于检查属性的不同结果

css - 选择不以字符串开头的类

javascript - 关闭窗口时触发ajax调用

html - 样式 <a> 链接一次不同的样式

html - 溢出导致的padding bottom : auto

html - nth-of-type 选择具有特定类别的前 3 个元素