gpt4 book ai didi

css - 当对象样式需要依赖于父容器时,我可以坚持容器和内容的 OOCSS 分离吗?

转载 作者:行者123 更新时间:2023-11-28 17:58:02 25 4
gpt4 key购买 nike

我的问题不同于 this one ,但它是关于相同的原则,所以这句话在这里也相关:

来自 https://github.com/stubbornella/oocss/wiki

Essentially, this means “rarely use location-dependent styles”. An object should look the same no matter where you put it. So instead of styling a specific h2 with .myObject h2 {...}, create and apply a class that describes the h2 in question, like h2 class="category".

但是,如果设计要求对象在特定容器内时其样式会发生变化怎么办?这是我的问题的一个简化示例。假设有一个名为 foo 的对象和一个名为 bar 的容器对象。 foo 和 bar 有它们自己的独立于位置的样式:

.foo {
...
}
.bar {
...
}

但是当 foo 像这样位于容器 bar 内时,当用户将鼠标悬停在 bar 上时,它的颜色需要改变:

<div class="bar">
...
<div class="foo">
...
</div>
...
</div>

在这种情况下,您似乎无法避免编写如下所示的依赖于位置的选择器:

.bar:hover .foo {
// color style
}

我想到的一个解决方案是引入一个显式依赖 bar 的类(使用 BEM naming convention 命名以明确父子关系),并将其添加到 foo 对象中:

<div class="bar">
...
<div class="foo bar__foo">
...
</div>
...
</div>

.bar:hover .bar__foo {
// color style
}

我想确认一下,这是处理问题的好方法吗? OOCSS还有其他方法吗?

最佳答案

这里最大的问题不是您将类链接在一起,而是您的类与位置无关。嵌套将会发生。 OOCSS 之类的方法很棒,因为它们可以帮助您了解何时出现嵌套和类命名等问题。

Mark Otto 上周发布了代码指南和 here are some relevant points:

  • Keep selectors short and strive to limit the number of elements in each selector to three.
  • Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).

他还提供了这些例子:

/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

简而言之:旨在将一个类的范围限定到它的父类。不要超过 3 个选择器。

你没问题:

.bar:hover .foo { ... } 

延伸阅读

关于css - 当对象样式需要依赖于父容器时,我可以坚持容器和内容的 OOCSS 分离吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com