英文:
How can I use :has() parent-selector to select a child element of a parent on the condition there are not intermediaries between parent and child?
问题
我正在尝试进行一些高级的自动颜色对比度校正工作。我使用Tailwind,并尝试创建一些CSS规则,当对比度过低时自动更改颜色。
假设以下情况:
.bg-white .text-white {
color: black;
}
简单。我们自动将白色背景上的白色文本更改为白色背景上的黑色文本。每当有人指定.text-white
时,他们不再需要担心由于无法控制的更高级别指定的其他背景颜色会违反WCAG辅助性准则。
然而,这就是我们的问题开始的地方。以下HTML将使白色文本不可读:
<div class="bg-white">
<div class="bg-black">
<span class="text-white">I was legible until you tried to be smart.</span>
</div>
</div>
有许多方法可以解决这个难题,但我想知道的是,是否可以使用:has()
选择器来实现这一点。
我想要的类似于以下内容:
.bg-white:not(:has(class*="bg-")) .text-white {
color: black;
}
我希望这表示“选择任何在bg-white
内部的text-white
,它没有任何其他类似于bg-
的类,因为这会更改背景颜色。
我的目标是,只有更改颜色的最直接的类被认为是背景颜色。
英文:
I am trying to do some fancy auto-color contrast correction work. I use Tailwind, and am trying to create some CSS rules that automatically change the color when the contrast is too low.
Assume the following:
.bg-white .text-white {
color: black;
}
Easy. We automatically change white text on a white background, into black text on a white background. Whenever someone specifies .text-white
, they no longer have to worry that another background color specified higher up out of their control, is going to break the WCAG Accessibility guidelines.
This is where our problem begins however. The following HTML will render the white text illegible:
<div class="bg-white">
<div class="bg-black">
<span class="text-white">I was legible until you tried to be smart.</span>
</div>
</div>
There are many ways I could solve this conundrum; but what I want to know, is if there is a way to achieve this with the :has() selector.
I would like something like the following:
.bg-white:not(:has(class*="bg-")) .text-white {
color: black;
}
I'm hoping that I am saying "Select any text-white which is inside a bg-white, which does not have any other elements with a class similar to "bg-" because this would change the background color.
My goal is to make it so that only the most immediate class which changes color is presumed to be the background color.
答案1
得分: 1
你差不多做得很好。你漏掉了[]
.bg-white:not(:has([class*="bg-"])) .text-white {
color: red;
}
<div class="bg-white">
<div class="bg-black">
<span class="text-white">在你试图聪明才绝的时候我还是可以阅读的</span>
</div>
</div>
<div class="bg-white">
<span class="text-white">在你试图聪明才绝的时候我还是可以阅读的。</span>
</div>
英文:
You are almost good. You are missing the []
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.bg-white:not(:has([class*="bg-"])) .text-white {
color: red;
}
<!-- language: lang-html -->
<div class="bg-white">
<div class="bg-black">
<span class="text-white">I was legible until you tried to be smart</span>
</div>
</div>
<div class="bg-white">
<span class="text-white">I was legible until you tried to be smart.</span>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论