【问题标题】:How to select the child elements of a particular element without having to type the name of parent again and again? [duplicate]如何选择特定元素的子元素而不必一次又一次地键入父元素的名称? [复制]
【发布时间】:2021-08-03 20:03:32
【问题描述】:

我想做类似的事情 CSS:

.parent {
  height: 100px;
  width: 100px;
  background-color: black;

  .child {
    height: 50px;
    width: 50px;
    background-color: red;
  }
}

HTML:

<div class="parent">
  <div class="child">
  </div>
</div>

但这不起作用。我必须这样做:

.parent {
  height: 100px;
  width: 100px;
  background-color: black;
}

.parent .child {
  height: 50px;
  width: 50px;
  background-color: red;
}

如果父元素中有很多子元素,我将不得不一次又一次地键入父名称。有什么捷径可以做到吗?

【问题讨论】:

  • 伙伴,你可以让它在父母之外......就像你设置父母一样,你设置孩子:.parent { height: 100px;宽度:100px;背景颜色:黑色; } .child { 高度:50px;宽度:50px;背景颜色:红色; }
  • 试试scss,支持嵌套等多种功能
  • 我们可能会在未来的 CSS 版本中得到这个 - drafts.csswg.org/css-nesting
  • @NoobDEV-GBL 我想将 css 属性仅应用于 .parent 中的 .child。如果我把它放在外面,它将应用于我不想要的类名为“child”的所有类
  • @noob_coder 是的,我知道,这就是我删除答案的原因

标签: html css


【解决方案1】:

您尝试使用 css(嵌套相关样式)执行的操作需要预处理器。我会推荐阅读Sass

如果您想非常具体,并且仅将这些属性应用于.parent 中具有.child 类的元素,则您需要在实际选择器之前拥有父选择器。 (.parent .child { })

如果您想将其应用于所有具有 .child 类的元素,您可以直接应用样式,而无需指定父选择器。

.child {
  height: 50px;
  width: 50px;
  background-color: red;
}

.parent {
  height: 100px;
  width: 100px;
  background-color: black;
}
<div class="parent">
  <div class="child">
  </div>
</div>

【讨论】:

    【解决方案2】:

    使用SCSS,可以进行多级嵌套。

    除了该功能之外,SCSS-lang 还提供了其他漂亮的功能。查看官方site

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多