gpt4 book ai didi

html - 嵌套 CSS 类——子类覆盖父类?

转载 作者:行者123 更新时间:2023-12-04 13:35:16 33 4
gpt4 key购买 nike

目标是让元素的父元素决定它的样式。所以 .dark .light p 会有浅色文本,.dark p 会有深色文本,而 .light .dark .light p 会有浅色文字。

p 元素甚至可能不是 .dark.light 的直接子元素,所以 .light .dark div。 wrap div.inner p 会有深色文本。

由于CSS的级联特性,似乎更倾向于最后一条规则。这可能吗?

/* Doesn't work - switching the order isn't helpful
as the opposite problem occurs */

.dark p {
color: #000;
}
.light p {
color: #aaa;
}
/* Works, but in my use case I need to specify attributes on
specific element. */

/*
.dark {
color: #000;
}

.light {
color: #aaa;
}
*/

/* Works but not realistic if paragraph is nested deeper */

/*
.dark > p {
color: #000;
}

.light > p {
color: #aaa;
}
*/

/* Only works on the first two levels */

/*
.dark p {
color: #000;
}

.light p {
color: #aaa;
}

.dark .light p {
color: #aaa;
}

.light .dark p {
color: #000;
}
*/
<div class="light">
<p>Light text</p>
<div class="dark">
<p>Dark text</p>
<div class="light">
<p>Light text</p>
</div>
</div>
</div>

<div class="dark">
<p>Dark text</p>
<div class="light">
<p>Light text</p>
<div class="dark">
<p>Dark text</p>
</div>
</div>
</div>

http://codepen.io/acondiff/pen/KaaqxP

最佳答案

CSS 遵循 css 文档的流程,因此如果 .dark 在 CSS 文件中出现在 .light 之后,那么您的 html 中具有这两个类的任何元素将始终显示.dark 风格。

.light {
background: #ccc;
}
.dark {
background: #999;
}
<p class="dark light">This will be dark  as it comes after light in the css file.</p>

!重要

您可以通过将 !important 放在 .light 样式上来覆盖 .dark 样式。

.light {
background: #eee !important;
}
.dark {
background: #999;
}
<p class="light dark">This will be light as the light styles has !important</p>

或者,您可以将灯光样式应用于所有元素,并只覆盖您需要的元素:

p {
background: #eee;
}
.dark {
background: #999;
}
<p>this will be light</p>

<p class="dark">this will be dark</p>

关于html - 嵌套 CSS 类——子类覆盖父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41730372/

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