CSS Reference

Css properties, css :nth-child() selector.

How to use the :nth-child() selector:

More "Try it Yourself" examples below.

Definition and Usage

The :nth-child( n ) selector matches every element that is the n th child of its parent.

n can be a number, a keyword (odd or even), or a formula (like an + b ).

Tip: Look at the :nth-of-type() selector to select the element that is the n th child, of the same type (tag name) , of its parent.

Browser Support

The numbers in the table specifies the first browser version that fully supports the selector.

Advertisement

More Examples

Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).

Here, we specify two different background colors for odd and even p elements:

Using a formula ( an + b ). Description: a represents a cycle size, n is a counter (starts at 0), and b is an offset value.

Here, we specify a background color for all p elements whose index is a multiple of 3 (will select the third, sixth, ninth, etc):

Here, we specify a background color for all p elements whose index is a multiple of 3. Then we subtract 1 (will select the second, fifth, eight, etc):

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Skip to main content
  • Select language
  • Skip to search

Full example

The :nth-child(an+b) CSS pseudo-class matches an element that has a n+ b -1 siblings before it, where n is positive or zero. More simply stated, the selector matches elements whose numeric position in a series of siblings matches the pattern an+b .

Some notes:

  • 0n+3 , or simply 3 , matches the third element.
  • 1n+0 , or simply n , matches every element. (Compatibility note: n does not match on Android Browser 4.3 and below whereas 1n does. 1n is equivalent to 1n+0 . Feel free to use whichever looks better.)
  • 2n+0 , or simply 2n , matches elements 2, 4, 6, 8, etc. You can substitute the keyword even for this expression.
  • 2n+1 matches elements 1, 3, 5, 7, etc. You can substitute the keyword odd for this expression.
  • 3n+4 matches elements 4, 7, 10, 13, etc.

The values a and b must both be integers, and the index of an element's first child is 1. In other words, this class matches all children whose indexes fall in the set { an + b; n = 0, 1, 2, ... }.

where <nth> = <an-plus-b> | even | odd

Example selectors

The following HTML...

...using this CSS...

...will result in:

Specifications

Browser compatibility.

[1] Opera can't handle dynamic insertion of elements.

[2] Gecko doesn't implement this feature yet. See bug 854148 .

[3] See bug 1300374 .

  • :nth-of-type
  • :first-child
  • :last-child

Document Tags and Contributors

  • CSS Pseudo-class
  • CSS Reference
  • CSS Selectors
  • Using the :target pseudo-class in selectors
  • Type selectors
  • Class selectors
  • ID selectors
  • Universal selectors
  • Attribute selectors
  • Adjacent sibling selectors
  • General sibling selectors
  • combinator separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first. By contrast, when two selectors are combined with the descendant selector, the combined selector expression matches those elements matched by the second selector for which there exists an ancestor element matched by the first selector, regardless of the number of "hops" up the DOM.'> Child selectors
  • Descendant selectors
  • , <area>, or <link> element with an href attribute. Thus, it matches all elements that match :link or :visited."> :any-link
  • ), checkbox (<input type="checkbox">) or option (<option> in a <select>) element that is checked or toggled to an on state. The user can change this state by clicking on the element, or selecting a different value, in which case the :checked pseudo-class no longer applies to this element, but will to the relevant one.'> :checked
  • :first-of-type
  • :fullscreen
  • :focus-within
  • :indeterminate
  • element is inside the range limits specified by the min and max attributes."> :in-range
  • or <form> element whose content fails to validate according to the input's attribute settings. This allows you to easily have invalid fields adopt an appearance that helps the user identify and correct errors."> :invalid
  • element, and possibly by information from the protocol (such as HTTP headers)."> :lang
  • :last-of-type
  • :nth-last-child
  • :nth-last-of-type
  • :only-child
  • :only-of-type
  • or <textarea> element that does not have the required attribute set on it. This allows forms to easily indicate optional fields, and to style them accordingly."> :optional
  • :out-of-range
  • :placeholder-shown
  • :read-write
  •  element that has the required attribute set on it. This allows forms to easily indicate which fields must have valid data before the form can be submitted."> :required
  • element and is identical to the selector html, except that its specificity is higher."> :root
  • . If no such attribute is used on an HTML page, the reference point is the <html> element."> :scope
  • or <form> element whose content validates correctly according to the input's type setting. This allows to easily make valid fields adopt an appearance that helps the user confirm that their data is formatted properly."> :valid
  •  element that represents the amount of progress that has happened so far. This lets you, for example, change the color of progress bars."> ::-moz-progress-bar
  • of type="range", which corresponds to values lower than the value currently selected by the thumb.'> ::-moz-range-progress
  • of type="range" to alter its numerical value.'> ::-moz-range-thumb
  • of type="range" slides.'> ::-moz-range-track
  • element. This pseudo-element is non-standard and specific to Internet Explorer 10+, hence the vendor prefix."> ::-ms-fill
  • of type="range", which corresponds to values lower than the value currently selected by the thumb.'> ::-ms-fill-lower
  • of type="range", which corresponds to values greater than the value currently selected by the thumb.'> ::-ms-fill-upper
  • ::-ms-thumb
  • ::-ms-track
  • element. Normally it's only visible as the unfilled portion of the bar, since by default it's rendered below the ::-webkit-progress-value pseudo-element. It is a child of the ::-webkit-progress-inner-element pseudo-element and the parent of the ::-webkit-progress-value pseudo-element."> ::-webkit-progress-bar
  • element. It is a child of the ::-webkit-progress-bar pseudo-element."> ::-webkit-progress-value
  • ::-webkit-slider-runnable-track
  • ::-webkit-slider-thumb
  • ::after (:after)
  • ::before (:before)
  • ::first-letter (:first-letter)
  • ::first-line (:first-line)
  • ::selection
  • ::cue (:cue)

:nth-child()

The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings.

Note that, in the element:nth-child() syntax, the child count includes children of any element type; but it is considered a match only if the element at that child position is of the specified element type.

:nth-child() takes a single argument that describes a pattern for matching element indices in a list of siblings. Element indices are 1-based.

Keyword values

Represents elements whose numeric position in a series of siblings is odd: 1, 3, 5, etc.

Represents elements whose numeric position in a series of siblings is even: 2, 4, 6, etc.

Functional notation

Represents elements whose numeric position in a series of siblings matches the pattern An+B , for every positive integer or zero value of n , where:

  • A is an integer step size,
  • B is an integer offset,
  • n is all nonnegative integers, starting from 0.

It can be read as the An+B -th element of a list. The A and B must both have <integer> values.

Example selectors

Represents the odd rows of an HTML table: 1, 3, 5, etc.

Represents the even rows of an HTML table: 2, 4, 6, etc.

Represents the seventh element.

Represents elements 5 [=5×1], 10 [=5×2], 15 [=5×3], etc. The first one to be returned as a result of the formula is 0 [=5x0], resulting in a no-match, since the elements are indexed from 1, whereas n starts from 0. This may seem weird at first, but it makes more sense when the B part of the formula is >0 , like in the next example.

Represents the seventh and all following elements: 7 [=0+7], 8 [=1+7], 9 [=2+7], etc.

Represents elements 4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], etc.

Represents the first three elements. [=-0+3, -1+3, -2+3]

Represents every <p> element in a group of siblings. This selects the same elements as a simple p selector (although with a higher specificity).

Represents every <p> that is the first element in a group of siblings. This is the same as the :first-child selector (and has the same specificity).

Represents the eighth through the fifteenth <p> elements of a group of siblings.

Detailed example

Specifications, browser compatibility.

  • :nth-of-type , :nth-last-child

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

Using :has() as a CSS Parent Selector and much more

Aug 18, 2022

by Jen Simmons

The basics of how to use :has() as a parent selector

A practical example using :has() with css grid, using :has() with the child combinator, using :has() with sibling combinators, styling form states without js, dark mode toggle with no js.

It’s been a long-standing dream of front-end developers to have a way to apply CSS to an element based on what’s happening inside that element.

Maybe we want to apply one layout to an article element if there’s a hero image at the top, and a different layout if there is no hero image. Or maybe we want to apply different styles to a form depending on the state of one of its input fields. How about giving a sidebar one background color if there’s a certain component in that sidebar, and a different background color if that component is not present? Use cases like these have been around for a long time, and web developers have repeatedly approached the CSS Working Group, begging them to invent a “parent selector”.

Over the last twenty years , the CSS Working Group discussed the possibility many, many times. The need was clear and well understood. Defining syntax was a doable task. But figuring out how a browser engine could handle potentially very complex circular patterns, and get through the calculations fast enough seemed impossible. Early versions of a parent selector were drafted for CSS3, only to be deferred. Finally, the :has() pseudo-class was officially defined in CSS Selectors level 4 . But having a web standard alone didn’t make :has() a reality. We still needed a browser team to figure out the very real performance challenge. In the meantime, computers continued to get more powerful and faster year after year.

In 2021, Igalia started advocating for :has() among browser engineering teams, prototyping their ideas and documenting their findings regarding performance. The renewed attention on :has() caught the attention of engineers who work on WebKit at Apple. We started implementing the pseudo-class, thinking through possibilities for the needed performance enhancements to make this work. We debated whether to start with a faster version with a very limited and narrow scope of what it could do, and then try to remove those limits if possible… or to start with something that had no limits, and only apply restrictions as required. We went for it, and implemented the more powerful version. We developed a number of novel :has -specific caching and filtering optimizations, and leveraged the existing advanced optimization strategies of our CSS engine. And our approach worked, proving that after a two decade wait, it is finally possible to implement such a selector with fantastic performance , even in the presence of large DOM trees and large numbers of :has() selectors.

The WebKit team shipped :has() in Safari Technology Preview 137 in December 2021, and in Safari 15.4 on March 14, 2022. Igalia did the engineering work to implement :has() in Chromium, which will ship in Chrome 105 on August 30, 2022. Presumably the other browsers built on Chromium won’t be far behind. Mozilla is currently working on the Firefox implementation.

So, let’s take a step-by-step hands-on look at what web developers can do with this desperately desired tool. It turns out, the :has() pseudo-class is not just a “parent selector”. After decades of dead-ends, this selector can do far more.

Let’s start with the basics. Imagine we want to style a <figure> element based on the kind of content in the figure. Sometimes our figure wraps only an image.

While other times there’s an image with a caption.

Now let’s apply some styles to the figure that will only apply if there is a figcaption inside the figure.

This selector means what it says — any figure element that has a figcaption inside will be selected.

Here’s the demo, if you’d like to alter the code and see what happens. Be sure to use a browser that supports :has() — as of today, that’s Safari.

See the Pen :has() demo — Figure variations by Jen Simmons ( @jensimmons ) on CodePen .

In this demo, I also target any figure that contains a pre element by using figure:has(pre) .

And I use a Selector Feature Query to hide a reminder about browser support whenever the current browser supports :has() .

The @supports selector() at-rule is itself very well supported . It can be incredibly useful anytime you want to use a feature query to test for browser support of a particular selector.

And finally, in this first demo, I also write a complex selector using the :not() pseudo-class . I want to apply display: flex to the figure — but only if an image is the sole content. Flexbox makes the image stretch to fill all available space.

I use a selector to target any figure that does not have any element that is not an image. If the figure has a figcaption , pre , p , or an h1 — or any element at all besides img — then the selector doesn’t apply.

:has() is a powerful thing.

Let’s look at a second demo where I’ve used :has() as a parent selector to easily solve a very practical need.

I have several article teaser cards laid out using CSS Grid. Some cards contain only headlines and text, while others also have an image. I want the cards with images to take up more space on the grid than those without images.

I don’t want to have to do extra work to get my content management system to apply a class or to use JavaScript for layout. I just want to write a simple selector in CSS that will tell the browser to make any teaser card with an image to take up two rows and two columns in the grid.

The :has() pseudo-class makes this simple:

See the Pen :has() demo — teaser cards by Jen Simmons ( @jensimmons ) on CodePen .

These first two demos use simple element selectors from the early days of CSS, but all of the selectors can be combined with :has() , including the class selector , the ID selector , the attribute selector — and powerful combinators.

First, a quick review of the difference between the descendant combinator and the child combinator ( > ).

The descendant combinator has been around since the very beginning of CSS. It’s the fancy name for when we put a space between two simple selectors. Like this:

This targets all img elements that are contained within an a element, no matter how far apart the a and the img are in the HTML DOM tree.

Child combinator is the name for when we put an > between two selectors — which tells the browser to target anything that matches the second selector, but only when the second selector is a direct child of the first.

For example, this selector targets all img elements wrapped by an a element, but only when the img is immediately after the a in the HTML.

With that in mind, let’s consider the difference between the following two examples. Both select the a element, rather than the img , since we are using :has() .

The first selects any a element with an img inside — any place in the HTML structure. While the second selects an element only if the img is a direct child of the a .

Both can be useful; they accomplish different things.

See the Pen :has() — descendant combinator vs child combinator by Jen Simmons ( @jensimmons ) on CodePen .

There are two additional types of combinators — both are siblings. And it’s through these that :has() becomes more than a parent selector.

Let’s review the two selectors with sibling relationships. There’s the next-sibling combinator ( + ) and the subsequent-sibling combinator ( ~ ).

The next-sibling combinator ( + ) selects only the paragraphs that come directly after an h2 element.

The subsequent-sibling combinator ( ~ ) selects all paragraphs that come after an h2 element. They must be siblings, but there can be any number of other HTML elements in between.

Note that both h2 + p and h2 ~ p select the paragraph elements, and not the h2 headlines. Like other selectors (think of a img ), it’s the last element listed that is targeted by the selector. But what if we want to target the h2 ? We can use sibling combinators with :has().

How often have you wanted to adjust the margins on a headline based on the element following it? Now it’s easy. This code allows us to select any h2 with a p immediately after it.

What if we want to do this for all six headline elements, without writing out six copies of the selector. We can use :is to simplify our code.

Or what if we want to write this code for more elements than just paragrapahs? Let’s eliminate the bottom margin of all headlines whenever they are followed by paragraphs, captions, code examples and lists.

Combining :has() with descendant combinators , child combinators ( > ), next-sibling combinators ( + ), and subsequent-sibling combinators ( ~ ) opens up a world of possibilities. But oh, this is still just the beginning.

There are a lot of fantastic pseudo-classes that can be used inside :has() . In fact, it revolutionizes what pseudo-classes can do. Previously, pseudo-classes were only used for styling an element based on a special state — or styling one of its children. Now, pseudo-classes can be used to capture state, without JavaScript, and style anything in the DOM based on that state.

Form input fields provide a powerful way to capture such a state. Form-specific pseudo-classes include :autofill , :enabled , :disabled , :read-only , :read-write , :placeholder-shown , :default , :checked , :indeterminate , :valid , :invalid , :in-range , :out-of-range , :required and :optional .

Let’s solve one of the use cases I described in the introduction — the long-standing need to style a form label based on the state of the input field. Let’s start with a basic form.

I’d like to apply a background to the whole form whenever one of the fields is in focus.

Now I could have used form:focus-within instead, but it would behave like form:has(:focus) . The :focus pseudo-class always applies CSS whenever a field is in focus. The :focus-visible pseudo-class provides a reliable way to style a focus indicator only when the browser would draw one natively, using the same complex heuristics the browser uses to determine whether or not to apply a focus-ring.

Now, let’s imagine I want to style the other fields, the ones not in focus — changing their label text color and the input border color. Before :has() , this required JavaScript. Now we can use this CSS.

What does that selector say? If one of the controls inside this form has focus, and the input element for this particular form control does not have focus, then change the color of this label’s text to peru . And change the border of the input field to be 2px solid peru .

You can see this code in action in the following demo by clicking inside one of the text fields. The background of the form changes, as I described earlier. And the label and input border colors of the fields that are not in focus also change.

See the Pen :has() demo: Forms by Jen Simmons ( @jensimmons ) on CodePen .

In this same demo, I would also like to improve the warning to the user when there’s an error in how they filled out the form. For years, we’ve been able to easily put a red box around an invalid input with this CSS.

Now with :has() , we can turn the label text red as well:

You can see the result by typing something in the website or email field that’s not a fully-formed URL or email address. Both are invalid, and so both will trigger a red border and red label, with an “X”.

And last, in this same demo I’m using a checkbox to allow the user to toggle between a light and dark theme.

I’ve styled the dark mode checkbox using custom styles, but it does still look like a checkbox. With more complex styles, I could create a toggle in CSS .

In a similar fashion, I could use a select menu to provide a user with multiple themes for my site.

See the Pen :has() Demo #5 — Theme picker via Select by Jen Simmons ( @jensimmons ) on CodePen .

Any time there’s an opportunity to use CSS instead of JavaScript, I’ll take it. This results in a faster experience and a more robust website. JavaScript can do amazing things, and we should use it when it’s the right tool for the job. But if we can accomplish the same result in HTML and CSS alone, that’s even better.

Looking through other pseudo-classes , there are so many that can be combined with :has() . Imagine the possibilities with :nth-child , :nth-last-child , :first-child , :last-child , :only-child , :nth-of-type , :nth-last-of-type , :first-of-type , :last-of-type , :only-of-type . The brand new :modal pseudo-class is triggered when a dialog is in the open state. With :has(:modal) you can style anything in the DOM based on whether the dialog is open or closed.

However, not every pseudo-class is currently supported inside :has() in every browser, so do try out your code in multiple browsers. Currently the dynamic media pseudo-classes don’t work — like :playing , :paused , :muted , etc. They very well may work in the future, so if you are reading this in the future, test them out! Also, form invalidation support is currently missing in certain specific situations, so dynamic state changes to those pseudo-classes may not update with :has() .

Safari 16 will add support for :has(:target) opening up interesting possibilities for writing code that looks at the current URL for a fragment that matches the ID of a specific element. For example, if a user clicks on a table of contents at the top of a document, and jumps down to the section of the page matching that link, :target provides a way to style that content uniquely, based on the fact the user clicked the link to get there. And :has() opens up what such styling can do.

Something to note — the CSS Working Group resolved to disallow all existing pseudo-elements inside of :has() . For example, article:has(p::first-line) and ol:has(li::marker) won’t work. Same with ::before and ::after.

The :has() revolution

This feels like a revolution in how we will write CSS selectors, opening up a world of possibilities previously either impossible or often not worth the effort. It feels like while we might recognize immediately how useful :has() will be, we also have no idea what is truly possible. Over the next several years, people who make demos and dive deep into what CSS can do will come up with amazing ideas, stretching :has() to its limits.

Michelle Barker created a fantastic demo that triggers the animation of Grid track sizes through the use of :has() and hover states. Read more about it in her blog post . Support for animated grid tracks will ship in Safari 16 . You can try out this demo today in Safari Technology Preview or Safari 16 beta .

The hardest part of :has() will be opening our minds to its possibilities. We’ve become so used to the limits imposed on us by not having a parent selector. Now, we have to break those habits.

That’s all the more reason to use vanilla CSS, and not limit yourself to the classes defined in a framework. By writing your own CSS, custom for your project, you can fully leverage all the powerful abilities of today’s browsers.

What will you use :has() for? Last December, I asked on Twitter what use cases folks might have for :has() , and got lots of replies with incredible ideas. I can’t wait to see yours.

@supports selector()

Avatar of Chris Coyier

I didn’t realize the support for @supports determining selector support was so good ! I usually think of @supports as a way to test for property: value pair support. But with the selector() function, we can test for selector support as well. It looks like this:

You just drop the selector right between the parens and that’s what it tests for.

That selector above is a pretty good test, actually. It’s a “selector list argument” that works for the :nth-child ‘n’ friends selectors. As I write, it’s only supported in Safari.

So let’s say your ideal situation is that the browser supports this selector. Here’s an example. You know that with <ol> and <ul> the only valid child element is <li> . But also say this list needs separators, so you (and I’m not saying this is a great idea) did this kind of thing:

Then you also want to zebra-stripe the list. And, if you want zebra striping, you need to select every other .list-item , ignoring the .separator . So…

But only Safari supports that… so you can do:

If you didn’t care what the fallback was, you wouldn’t even have to bother with the @supports at all. But say you do care about the fallback. Perhaps in the supported situation, the zebra striping does the heavy lifting of the UX you are shooting for, so all you need for the seperator is a bit of space. But for non-supporting browsers, you’ll need something beefier because you don’t have the zebra striping.

So now you can style both situations:

If we get the @when syntax, then we can write it a little cleaner:

Anyway. The end result is…

safari nth child

There is a JavaScript API for testing support as well. I wasn’t sure if this would actually work, but it appears to! This fails in Chrome and passes in Safari as I write:

While I was putting this together, I was thinking… hmmmmmmm — what CSS selectors are out there that have weird cross-browser support? It’s really not that many. And even of those that do have weird cross-browser support, thinking of the number of use-cases where you care to actually wrap it in an @supports (rather than just let it fail) is fairly few.

The ::marker pseudo-element would have been a great one, but it’s pretty well supported now. I was thinking the case-insensitive attribute selector, like [href$="pdf" i] , would have been a good one, but nope, also well supported. Same deal with the comma-separated :not(a, .b, [c]) . Maybe something like :fullscreen / :-webkit-full-screen would be interesting and useful because it’s uniquely not supported in iOS Safari?

What is the ‘i’ at the end of this: [href$=”pdf” i]

Never mind: [attr operator value i] Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Copy and paste this code: micuno *

Leave this field empty

  • Skip to main content

UDN Web Docs: MDN Backup

  • :nth-child()

The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.

The nth-child pseudo-class is specified with a single argument that describes a pattern for matching element indices in a list of siblings. Element indices are 1-based.

Keyword values

Functional notation, formal syntax.

where <nth> = <an-plus-b> | even | odd <complex-selector-list> = <complex-selector> #

where <complex-selector> = <compound-selector> [ <combinator> ? <compound-selector> ] *

where <compound-selector> = [ <type-selector> ? <subclass-selector> * [ <pseudo-element-selector> <pseudo-class-selector> * ] * ] ! <combinator> = '>' | ' + ' | '~' | [ '|' ]

where <type-selector> = <wq-name> | <ns-prefix> ? ' * ' <subclass-selector> = <id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector> <pseudo-element-selector> = ':' <pseudo-class-selector> <pseudo-class-selector> = ':' <ident-token> | ':' <function-token> <any-value> ')'

where <wq-name> = <ns-prefix> ? <ident-token> <ns-prefix> = [ <ident-token> | ' * ' ] ? | <id-selector> = <hash-token> <class-selector> = '.' <ident-token> <attribute-selector> = '[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier> ? ']'

where <attr-matcher> = [ '~' | | | '^' | '$' | ' * ' ] ? '=' <attr-modifier> = i | s

Example selectors

Detailed example, specifications, browser compatibility.

  • :nth-of-type , :nth-last-child
  • CSS Reference
  • CSS Selectors
  • Using the :target pseudo-class in selectors
  • Selector list
  • Type selectors
  • Class selectors
  • ID selectors
  • Universal selectors
  • Attribute selectors
  • Adjacent sibling combinator
  • General sibling combinator
  • Child combinator
  • Descendant combinator
  • Column combinator
  • :first-child
  • :first-of-type
  • :fullscreen
  • :focus-visible
  • :focus-within
  • :host-context()
  • :indeterminate
  • :is() (:matches(), :any())
  • :last-child
  • :last-of-type
  • :nth-last-child()
  • :nth-last-of-type()
  • :nth-of-type()
  • :only-child
  • :only-of-type
  • :out-of-range
  • :placeholder-shown
  • :read-write
  • ::-moz-progress-bar
  • ::-moz-range-progress
  • ::-moz-range-thumb
  • ::-moz-range-track
  • ::-webkit-progress-bar
  • ::-webkit-progress-value
  • ::-webkit-slider-runnable-track
  • ::-webkit-slider-thumb
  • ::after (:after)
  • ::before (:before)
  • ::cue-region
  • ::first-letter (:first-letter)
  • ::first-line (:first-line)
  • ::grammar-error
  • ::placeholder
  • ::selection
  • ::slotted()
  • ::spelling-error

12 CSS :nth-child() Examples

Collection of hand-picked free HTML and pure CSS :nth-child() code examples from Codepen and other resources.

Demo image: Retro Neon with nth-child

  • ItsMeNatalie
  • December 7, 2019
  • demo and code
  • HTML / CSS (SCSS)

About a code

Retro neon with nth-child.

Compatible browsers: Chrome, Edge, Firefox, Opera, Safari

Responsive: no

Dependencies: -

Demo image: nth-child

  • December 6, 2019

Demo image: 12 nth Selectors

  • Gabriele Corti

12 nth Selectors

  • Ryan Mulligan
  • December 5, 2019

0123456789 Rhymes

Responsive: yes

  • Katy Cassidy

Henry the nth-child(8)

Demo image: Triangle Grid with nth-child

  • Stephen Lee
  • December 4, 2019
  • HTML (Haml) / CSS (SCSS)

Triangle Grid with nth-child

Creating a grid of triangles with CSS Grid and custom properties.

Demo image: nth-child

  • December 3, 2019
  • HTML / CSS (SCSS) / JS

CSS Pattern Using :nth Selector

Demo image: Alphabet

  • Ludmila Tretyakova

Demo image: :nth-child Flower

  • Tyler Durrett
  • HTML (Pug) / CSS (SCSS)

:nth-child Flower

It uses nth-child selection to affect the hue of the petals. Try changing the .select-2 class in the HTML with any number from 1 to 20 (e.g. .select-13 ) to get a feel for how that works.

Demo image: :nth-child

  • December 2, 2019

CSS selector: `:nth-child()`: Matches elements with no parent

  • 6 - 10 : Not supported
  • 11 : Not supported
  • 12 - 18 : Not supported
  • 79 - 123 : Supported
  • 124 : Supported
  • 2 - 51 : Not supported
  • 52 - 124 : Supported
  • 125 : Supported
  • 126 - 128 : Supported
  • 4 - 56 : Not supported
  • 57 - 123 : Supported
  • 125 - 127 : Supported
  • 3.1 - 17.3 : Not supported
  • 17.4 : Not supported
  • 17.5 : Not supported
  • TP : Support unknown
  • 10 - 43 : Not supported
  • 44 - 108 : Supported
  • 109 : Supported

Safari on iOS

  • 3.2 - 17.3 : Not supported
  • all : Support unknown

Android Browser

  • 2.1 - 4.4.4 : Not supported

Opera Mobile

  • 12 - 12.1 : Not supported
  • 80 : Supported

Chrome for Android

Firefox for android, uc browser for android.

  • 15.5 : Support unknown

Samsung Internet

  • 4 - 6.4 : Not supported
  • 7.2 - 23 : Supported
  • 24 : Supported
  • 14.9 : Support unknown

Baidu Browser

  • 13.52 : Support unknown

KaiOS Browser

  • 2.5 : Support unknown
  • 3 : Support unknown

A rather geeky/technical weblog, est. 2001, by Bramus

CSS @​supports rules to target only Firefox / Safari / Chromium

Yesterday I took some time to rework my Houdini-powered CSS Gradient Border Animation Demo to include a fallback for non-Houdini browsers.

The plan of attack was pretty straightforward:

  • Manual frame-by-frame animations for non-Houdini browsers
  • Automagic Houdini-powered animations for browser with @property support

Only problem with that approach is that there’s currently no way to use @supports to directly detect whether a browser supports Houdini’s @property or not , so I got creative with @supports …

Houdini is a set of low-level APIs that exposes parts of the CSS engine, giving developers the power to extend CSS by hooking into the styling and layout process of a browser’s rendering engine. Houdini is a group of APIs that give developers direct access to the CSS Object Model (CSSOM), enabling developers to write code the browser can parse as CSS, thereby creating new CSS features without waiting for them to be implemented natively in browsers.

It really is magic, hence it's name Houdini. I'd recommend this slidedeck and this video to get you started

Join the Conversation

' src=

  • Pingback: Web Design & Development News: Collective #668 | Codrops

Hi Bramus, it looks like this is not working. I have both Brave (Chromium) and Safari open next to each other on my desktop and the “combined demo” are both showing blue.. (Safari should be red?). Has something changed with the specs on either of these browsers since 2021?

As mentioned in the post, these tests are really fragile and could stop working any time. I guess that time has come, as more browsers support many new features.

Leave a comment

Cancel reply.

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

IMAGES

  1. Safari With Kids & Families: The Best Destinations

    safari nth child

  2. How to Take a Child-Friendly African Safari

    safari nth child

  3. Aprenda a usar o :nth-child com um tutorial completo!

    safari nth child

  4. nth-childの使い方・要素の範囲や特定の要素を指定する方法

    safari nth child

  5. Family Safari in Africa, Kids on Safari, Packages, Destinations For

    safari nth child

  6. Live simple example of nth child selector in scss 2020

    safari nth child

VIDEO

  1. চিতা বাঘ এর ভয়ঙ্কর শিকার করার মুহূর্ত😱😱#wildlife #animals #cheetah #nature #leopard #safari #shorts

  2. 10 Places to Visit in Dubai

COMMENTS

  1. :nth-child()

    Represents the seventh element. :nth-child(5n) Represents elements 5 [=5×1], 10 [=5×2], 15 [=5×3], etc. The first one to be returned as a result of the formula is 0 [=5x0], resulting in a no-match, since the elements are indexed from 1, whereas n starts from 0. This may seem weird at first, but it makes more sense when the B part of the ...

  2. html

    I was having similar issues with displaying :nth-childs as none, and changing it to :nth-of-type cleared it right up on Safari mobile. - Justin Medas Oct 21, 2014 at 14:08

  3. :nth-child

    The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+3) will select the first 3 li elements. The :nth-child selector is very similar to :nth-of-type but with one critical difference: it is less specific.

  4. The Difference Between :nth-child and :nth-of-type

    p:nth-of-type(2) { color: red; } There is a difference though of course. Our :nth-child selector above, in "Plain English," means select an element if: It is a paragraph element. It is the second child of a parent. Our :nth-of-type selector, in "Plain English," means: Select the second paragraph child of a parent.

  5. CSS :nth-child() Selector

    The :nth-child( n) selector matches every element that is the n th child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b ). Tip: Look at the :nth-of-type () selector to select the element that is the n th child, of the same type (tag name), of its parent. Version:

  6. How nth-child Works

    A progressive enhancement (at least for layout) way around the IE problem would be to use :nth-child(1n) along with the other :nth-child's. That way, every child element get's the code you need in browsers that support :nth-child, and for browsers that don't support it, just make sure that the fallback doesn't break the layout.

  7. :nth-child

    The :nth-child(an+b) CSS pseudo-class matches an element that has a n+ b -1 siblings before it, where n is positive or zero. More simply stated, the selector matches elements whose numeric position in a series of siblings matches the pattern an+b. /* Selects every fourth child element inside the body */. /* regardless of element type */.

  8. :nth-child

    The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings. W3cubDocs / CSS W3cubTools Cheatsheets About ... Safari on IOS Samsung Internet:nth-child: 1: 12: 3.5: 9: 9.5 Before Opera 15, Opera does not handle dynamically inserted elements for :nth-child(). 3.1: ≤37: 18: 4:

  9. CSS selector: `:nth-child()`

    CSS selector: :nth-child() CSS selector: :nth-child() See full reference on MDN Web Docs. 1 Before Opera 15, Opera does not handle dynamically inserted elements for :nth-child(). "Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.

  10. selector list argument of :nth-child and :nth-last-child CSS pseudo

    The newest versions of :nth-child() and :nth-last-child() accept an optional of S clause which filters the children to only those which match the selector list S.For example, :nth-child(1 of .foo) selects the first child among the children that have the foo class (ignoring any non-foo children which precede that child). Similar to :nth-of-type, but for arbitrary selectors instead of only type ...

  11. Using :has() as a CSS Parent Selector and much more

    Imagine the possibilities with :nth-child, :nth-last-child, :first-child, :last-child, ... Safari 16 will add support for :has(:target) opening up interesting possibilities for writing code that looks at the current URL for a fragment that matches the ID of a specific element.

  12. @supports selector()

    It looks like this: @supports selector(:nth-child(1 of .foo)) { } You just drop the selector right between the parens and that's what it tests for. That selector above is a pretty good test, actually. It's a "selector list argument" that works for the :nth-child 'n' friends selectors. As I write, it's only supported in Safari.

  13. :nth-child()

    p:nth-child(1) or p:nth-child(0n+1) Represents every <p> that is the first element in a group of siblings. This is the same as the :first-child selector (and has the same specificity). p:nth-child(n+8):nth-child(-n+15) Represents the eighth through the fifteenth <p> elements of a group of siblings. Detailed example HTML

  14. 12 CSS :nth-child() Examples

    About a code:nth-child Flower. It uses nth-child selection to affect the hue of the petals. Try changing the .select-2 class in the HTML with any number from 1 to 20 (e.g. .select-13) to get a feel for how that works.. Compatible browsers: Chrome, Edge, Firefox, Opera, Safari Responsive: yes Dependencies: -

  15. CSS selector: `:nth-child()`: Matches elements with no parent

    Support via Patreon. Become a caniuse Patron to support the site for only $1/month!

  16. CSS @ supports rules to target only Firefox / Safari / Chromium

    Safari is the only browser that supports the complex :nth-child(An+B [of S]?) selector — which itself allows you to create a :nth-of-class-like selector — so you can rely on that. Using selector() function in @supports we can check whether the browser supports it or not. /* Safari Only */ @supports selector(:nth-child(1 of x)) { …

  17. Browser Compatibility of css-nth-child-of on Safari Browsers

    css-nth-child-of property shows High browser compatibility on Safari browsers. High browser compatibility means the css-nth-child-of property is Fully Supported by a majority of Safari browser versions.

  18. CSS Selector for nth range?

    144. One more approach you could use is: .myTableRow td:nth-child(n+2):nth-child(-n+4){. background-color: #FFFFCC; } This is a little clearer because it includes the numbers in your range ( 2 and 4) instead of having to count backwards from the end. It's also a bit more robust because you don't have to consider the total number of items there are.

  19. Home

    To install the web app: Chrome (desktop) Open the settings dropdown in the top right corner of the browser. Choose "Install Nth Child..." Confirm the prompt. Chrome (Android) A prompt to "Add Nth Child to Home screen" should appear automatically. If it doesn't or if it was dismissed: