gpt4 book ai didi

css - CSS 标签限定(例如 h1.some-class)有什么问题?

转载 作者:行者123 更新时间:2023-12-02 18:02:02 24 4
gpt4 key购买 nike

有人可以向我解释一下为什么标签限定是一种不好的 CSS 实践吗?为什么 tag.class 在具有不言自明的元素的情况下不好?例如

<section class="carousel-item">

<header class="header of-carousel">
<h2 class="heading of-carousel">Services</h2>
</header>

<footer class="footer of-carousel">

</footer>

</section>

为什么它比带有上下文修饰符的 DRY 和简洁代码更好?

<section class="carousel-item">

<header class="of-carousel">
<h2 class="of-carousel">Services</h2>
</header>

<footer class="of-carousel">

</footer>

</section>

.of-carousel {
header.& {…}
h2.& {…}
footer.& {…}
}

甚至

section.carousel-item
header
h2
footer

.carousel-item {
header {…}
h2 {…}
footer {…}
}

我看到很多人沉迷于 BEM,但我不明白为什么?他们的选择器是如此丑陋,尤其是在 HTTP-2__ 时代。

最佳答案

我所熟悉的惯例是,如果选择器具有不同级别的特异性,那么限定就很糟糕。这就是说,用类或标签来限定 id 是没有意义的(因为 id 已经是唯一的),或者用标签来限定类(因为类应该比标签更唯一,并且如果你的目的是让一个类在两种不同的情况下做两种不同的事情,您应该通过使它们成为两个不同的类来提高可读性)。然而,我从未被告知使用类对类限定符是不好的做法(事实上,我怀疑 Bootstrap 纯粹根据其语法广泛使用了这些限定符)。

This article from MDN ,这是“css 标记限定”的热门搜索结果之一,似乎同意我的观点,至少在什么时候这是不好的做法:

If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.

它接着说:

The previous concept also applies [to qualifying a tag with a class]. Though classes can be used many times on the same page, they are still more unique than a tag. One convention you can use is to include the tag name in the class name. However, this may cost some flexibility; if design changes are made to the tag, the class names must be changed as well. (It’s best to choose strictly semantic names, as such flexibility is one of the aims of separate stylesheets.)

CSS Tricks似乎同意,说:

ID's are unique, so they don't need a tag name to go along with it. Doing so makes the selector less efficient. Don't do it with class names either, if you can avoid it. Classes aren't unique, so theoretically you could have a class name do something that could be useful on multiple different elements. And if you wanted to have that styling be different depending on the element, you might need to tag-qualify (e.g. li.first), but that's pretty rare, so in general, don't.

希望这有助于回答您的问题。

关于css - CSS 标签限定(例如 h1.some-class)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937112/

24 4 0