CSS 伪元素 - 仅针对当前元素,而不是后代

时间:2021-03-03 11:35:07

标签: css selector pseudo-element

如何定位当前元素上的伪元素而不是子元素的伪元素?

html 结构:

<label
   <input/>
</label>

css 代码:

.main-0-6-18 >input::before {
    /* the pseudo on children */

    display: block;
    height: 100%;
    width: 100%;
    content: "";
    /* blah-blah */
}

.main-0-6-18::before {
    /* the pseudo on parent */

    /* affects on children too */

    content: " ";
    display: inline;
    width: 0;
    overflow: hidden;
    visibility: hidden;
}

我尝试使用 .main-0-6-18>::before 但它不起作用。

enter image description here

1 个答案:

答案 0 :(得分:0)

正如the documentation所说:

<块引用>

在 CSS 中,::before 创建一个伪元素,它是被选元素的第一个子元素。

就您而言,您使用的是同一个类,因此它针对具有此类的所有元素。

父伪元素不会影响子伪元素

.parent::before {
  content: '';
  display: block;
  width: 40px;
  height: 40px;
  border: 1px solid black;
}
.child::before {
  content: '';
  display: block;
  width: 60px;
  height: 60px;
  background-color: red;
}
<div class="parent">
  <div class="child"></div>
</div>

相关问题