英文:
CSS selector to show top n child elements based on class conditions in parent element
问题
我有一个HTML布局,其中有一个面板,其中有几个具有类"field"的子div。其中一些子div具有类"hide"。
当面板具有类"ShowSingleRow"时,我希望只显示前4个不具有"hide"类的子div。
当面板没有类"ShowSingleRow"时,我希望只显示前8个不具有"hide"类的子div。这种情况在这里有效。
我尝试使用CSS选择器,如:not()、:nth-child()和:nth-of-type()来实现这一目标,但我没有得到期望的结果。
我认为问题出在**nth-of-type(-n+4)**上,在下面共享的示例中,我希望看到"one two four five"。它检查前四个子div并显示"one two four"(因为值为"three"的div具有"hide"类)。是否有一种方法可以检查前4个匹配的div,排除具有"hide"类的div?
我正在寻找一个通用的解决方案,其中子div的数量可能不同。
英文:
I have a HTML layout where there is a panel with several child divs that have the class "field". Some of these child divs have the class "hide".
When the panel has the class "ShowSingleRow", I want to display only the top 4 child divs that do not have the "hide" class.
When the panel does not have the "ShowSingleRow" class, I want to display only top 8 child divs that do not have the "hide" class. This scenario is working here.
I have tried using CSS selectors such as :not(), :nth-child(), and :nth-of-type() to achieve this, but I am not getting the desired result.
I think the issue is with nth-of-type(-n+4), in the example shared below, I want to see "one two four five". It checks first four child divs and shows "one two four" (as div with value "three" has "hide" class). Is there a way it can check top 4 matching divs excluding the ones with "hide" class?
I am looking for a generic solution where child divs can vary in count.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.panel>.field {
display: none;
}
.panel:not(.ShowSingleRow)>.field:not(.hide):nth-of-type(-n+8) {
display: inline-block;
}
.panel.ShowSingleRow>.field:not(.hide):nth-of-type(-n+4) {
display: inline-block;
}
<!-- language: lang-html -->
<div class="panel ShowSingleRow">
<div class="field">one</div>
<div class="field">two</div>
<div class="field hide">three</div>
<div class="field">four</div>
<div class="field">five</div>
<div class="field hide">six</div>
<div class="field">seven</div>
<div class="field">eight</div>
</div>
<!-- end snippet -->
答案1
得分: 1
.panel.ShowSingleRow > .field:nth-child(-n+4 of :not(.hide))
但是目前Firefox还不支持,其他Chromium浏览器可能需要一些时间才能提供支持。
英文:
Safari, and the next version of Chrome will support
.panel.ShowSingleRow>.field:nth-child(-n+4 of :not(.hide))
But there's no Firefox support yet, and other Chromium browsers may take some time to become available.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论