Web Front-end
CSS Tutorial
How to style elements based on the number of children they have with CSS?
How to style elements based on the number of children they have with CSS?
CSS cannot directly count children, but it can style parents based on child count using :has() with selectors like :first-child:last-child for exactly one child, :nth-child(N):last-child for exactly N children, or :nth-child(N) for at least N children—relying on existence checks rather than arithmetic.

You can’t directly count children with pure CSS, but you can style elements based on whether they have a specific number (or range) of children — using :nth-child(), :first-child, :last-child, and combinators. It’s limited, but practical for common cases like “only one child”, “exactly two”, or “more than three”.
Style an element that has exactly one child
This is the most reliable case: if an element has only one child, that child must be both the first and the last. So you can target it with :first-child:last-child.
:has(> :first-child:last-child) {
border: 2px solid green;
}
Note: :has() is supported in modern browsers (Chrome 105 , Safari 15.4 , Firefox 121 ), but not in older ones. Without :has(), you’d need to style the *child* instead — e.g., > :first-child:last-child — which only works if you control the child’s styling, not the parent’s.
Style a parent when it has *at least* N children
CSS can’t express “≥ N”, but you can approximate it by checking if the *Nth* child exists — using the general sibling combinator ~. For example, to detect ≥ 3 children:
:has(> :nth-child(3)) {
padding: 1rem;
}
This works because if there’s a third child, the selector matches. Same logic applies for ≥ 4 (:nth-child(4)), etc. Just remember: this only works with :has(). Without it, fallbacks require JavaScript or restructuring markup.
Style based on “only two children” or “exactly N”
For exactly two: the second child must exist (:nth-child(2)) and also be the last (:last-child). So:
:has(> :nth-child(2):last-child) {
background-color: #f0f0f0;
}
For exactly three: use :nth-child(3):last-child. The pattern is consistent — but again, depends on :has(). Also note: :nth-child(N) counts *all* siblings, not just matching elements — so whitespace-only text nodes don’t interfere, but other elements (e.g., <span></span>, <div>) do count.<h3 id="What-breaks-it-and-what-to-watch-for">What breaks it — and what to watch for</h3>
<p><code>:has() doesn’t work in pseudo-elements (::before, ::after), nor inside @keyframes or @media queries (yet). Also:
- Elements with
display: contentschildren are *not* counted as children — their children become direct children of the parent - Dynamic changes (e.g., adding/removing children via JS) trigger re-evaluation — but some older engines may lag or ignore updates
- If you need IE or pre-2022 browser support, you’ll need a
data-child-countattribute updated via JavaScript
The real constraint isn’t syntax — it’s that CSS has no native counter. Everything hinges on existence checks, not arithmetic. That’s why “exactly N” always reduces to “Nth exists AND it’s last” — and why zero-child detection requires :empty, not :has().
The above is the detailed content of How to style elements based on the number of children they have with CSS?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How does CSS manage component colors in different states_Using CSS pseudo-classes to cooperate with variable switching
Mar 06, 2026 pm 04:00 PM
How to use pseudo-classes such as :hover:focus and CSS variables to change colors. It is of course possible to directly change the color or background-color in the pseudo-class. However, once there are many states (such as :hover, :focus, :active, :disabled) and you want to change the theme color uniformly, hard-writing the color value four times will make it easy to miss changes and difficult to maintain. The correct approach is to extract the color into a variable and only overwrite the variable value in the pseudo class: :root{--btn-bg:#007bff;--btn-bg-hover:#0056b3;--btn-bg-active:#004085;}.btn
How CSS uses Less's Recursive Mixins to implement recursive logic_Generate complex CSS layout through loops
Mar 06, 2026 pm 01:22 PM
Less recursive mixins need to set clear termination conditions (such as counter decrement whenguard) to avoid infinite expansion; if there are more than 20 layers of explosive stacks, JS plug-ins or pre-generation should be used first; parameter passing must prevent variable overwriting, and splicing selectors should use @{var}; non-essential scenarios (such as simple repetition, responsive nesting) should not force recursion.
How to make a search bar that automatically fills the remaining space with CSS_Stretch the input box css through the Flex-grow attribute
Mar 06, 2026 pm 02:27 PM
To make the search box automatically fill the remaining space, you need to put the input into the display:flex container and set flex-grow:1; the parent container must enable Flex layout to avoid conflicts between width and flex-grow, and reset min-width:0 to prevent browser default restrictions.
CSS mobile performance optimization_Use will-change to inform transition attributes in advance
Mar 12, 2026 am 11:15 AM
Will-change should only be declared for transform and opacity attributes that will change frequently and can trigger synthesis; avoid abusing invalid attributes such as all, left, top, etc., which must be added/removed dynamically, and be used with caution in scrolling containers. Mobile terminals need to take into account compatibility and memory limitations.
How does CSS adapt to the layout of large-screen TV browsers such as TV_CSS styles optimized through long-distance interaction
Mar 05, 2026 pm 08:57 PM
TV browser disables:hover, you need to use:focus-visible to simulate focus; unit priority is vh/vw; scroll-snap needs to be combined with smooth; high-resolution screens use box-shadow scale to replace the 1px border.
How to avoid content overflow when using CSS with float_Set the box-sizing of the box model and ensure that the sum of the percentages does not exceed 100%
Mar 12, 2026 pm 12:00 PM
If the floating element cannot open the parent container, BFC needs to be triggered. Overflow:hidden is commonly used; box-sizing:border-box must be set on the floating element itself; the percentage exceeds 100% due to whitespace characters, border/padding and pixel rounding; in IE, pay attention to the box-sizing prefix and margin parsing bugs.
How to make a simple fixed bottom toolbar with CSS_Set bottom:0 through position:fixed
Mar 10, 2026 pm 02:12 PM
The main reason why bottom:0 does not take effect is that the ancestor element triggers transform/will-change/filter to create a new containing block, so that the fixed element is positioned relative to it rather than the viewport; dynamic changes in the iOS Safari address bar cause occlusion; fixed elements need to be given way with padding-bottom; z-index failure is often caused by the parent creating a cascading context.
How to customize core components of CSS through Bootstrap's Sass source code_modify variables and recompile the css framework
Mar 06, 2026 pm 01:54 PM
To make Bootstrap's $primary and other variables take effect, they must be imported in order in the custom SCSS file: first declare the variables, then import functions, variables, mixins, and finally import bootstrap; otherwise, the variables will fall back to their default values.





