Is it possible to utilize nth-child() without recursion?

Can the CSS selector parent child:nth-child() be used to target only children?

The HTML code is as follows:

<body>
    <div>div 1</div>
    <div>
        div 2
        <div>div 2.1</div>
        <div>div 2.2</div>
    </div>
</body>

I attempted to style div 1 & div 2 with CSS using:

body div:nth-of-type(1) {
    background: red;
    color: white;
}

body div:nth-child(2) {
    background: blue;
}

However, div 2.1 & 2.21 were also selected. Here is a link to the JSFiddle.

Is it possible to achieve non-recursive selection? If not, would using classes or IDs be the only solution?

Answer №1

If you want to target only the direct children of the body element, you can use a > selector between body and div:

body > div:nth-of-type(1) {
    background: red;
    color: white;
}

body > div:nth-child(2) {
    background: blue;
}
<body>
    <div>div 1</div>
    <div>
        div 2
        <div>div 2.1</div>
        <div>div 2.2</div>
    </div>
</body>

Answer №2

Using the ">" character as a parent-child selector is helpful in styling elements. To address the challenge of transparent default styles for 2.1 and 2.2, it's important to apply distinct styling:

Link to Example

div {
    background: white;
}

body > div:nth-of-type(1) {
    background: red;
    color: white;
}

body > div:nth-child(2) {
    background: blue;
}

Answer №3

A great alternative to pseudo-classes is using the direct child selector.

By simply utilizing the `>` symbol, you can achieve the desired results.

body > div {
  background: red;
  color: white;
}
body > div > div {
  background: blue;
  color: white;
  padding-left: 1em;
}
<body>
  <div>div 1</div>
  <div>
    div 2
    <div>div 2.1</div>
    <div>div 2.2</div>
  </div>
</body>

If you're interested in learning more, check out The 30 CSS Selectors you Must Memorize

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS: A guide to creating layouts

I wrote this code snippet to display a table: <div class="topologyBalloon" id="bl_c2f03b99-6d62-43c4-9a35-4b4cbf22a7db"> <a href="#close" class="closeTopologyBalloon">×</a> <div class="contentBody"> <table class="deta ...

Trouble with displaying <tr> inside <td> element

Why are my internal rows not appearing inside the td element? <tr id="group_1_id"> <th>Group 1</th> <td> <tr id="1"><td>1</td><td>One</td><td><input type="text" name="one" valu ...

Struggling to Collaborate with External PHP File Leads to Garbled Results

Recently started learning PHP and I'm pretty sure I have it set up correctly with my local IIS as I was able to use it in a form on another local website. For this particular project, I have a basic HTML file structured like this: <!doctype html&g ...

Animation is not applied to Bootstrap Collapse on a row within a table

My Bootstrap 4 table has an issue - when I apply the "collapse" class to a table row, it behaves differently compared to applying it to a div element. Clicking "animate div" smoothly animates the target div, but clicking "animate tr" does not animate the ...

programming for the final radio button text entry

I am struggling with a form that has 5 radio buttons, including an "other" option where users can manually enter text. The issue I'm facing is that the form only returns the manual entry text and not any of the preset radio values. I need it to work f ...

Comparing HTML5 and web services with MVC3

Within my organization, there is an ongoing discussion regarding the best approach to developing our future web applications. We currently have two distinct groups of developers who share common interests. All parties agree on utilizing html5, css3, and jQ ...

Steps to turn off the automatic completion feature for orders in WooCommerce on your WordPress website

Looking for assistance with changing the order status from completed to processing. When an order is placed, it automatically goes to completed status which is not the desired outcome. The status should change based on the virtual product purchased. I wou ...

How can I prevent opening duplicate tabs of the same website simultaneously?

Is there a way to prevent users from accessing the same website page from multiple tabs? Could this be accomplished using JavaScript? ...

Stream music from SoundCloud by simply clicking a button on an external source, no need

My post contains an embedded SoundCloud player using the following code: <iframe class="soundcloud_iframe" width="100%" height="166" scrolling="no" frameborder="no" src="'.esc_url('https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcl ...

jQuery SlideOver - Arranging Divs in a horizontal layout

Currently, I am working on an application wizard that is designed to slide panels in order to display different sections of the resume application. You can view my site here: . The issue I am having is that when you click anywhere on the form, the panels a ...

Looking to troubleshoot the selenium error in a loop, specifically the InvalidSelectorException that states: "invalid selector: Unable to find element with the specified xpath"?

I have been attempting to create a for loop in selenium that checks if certain buttons on a website are clickable, clicks on them, and refreshes the page until they are. However, I am encountering an error with my Xpaths as shown below (InvalidSelectorExce ...

authentication routing procedure

My web portal for event bookings initially allows users to choose tickets without logging in. However, when it comes time to make a payment, the user must sign in. I have set up a redirect to the sign-in page and then back to the main page of the portal wh ...

Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs? I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is ...

Revamp the md-select Container

Hello there! I'm looking for a stylish way to revamp the design of the md-select Window. Specifically, I aim to customize the background and hover effects. Despite my attempts to modify the .md-select-menu-container in CSS, it proved unsuccessful. I ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

Adjust the jQuery resizable handlers on the fly

I am encountering an issue when attempting to change the handler on a resizable element. Initially, I used : $(line) .draggable({containment:"parent"}) .resizable({ containment:"parent", handles: "e, w" }); N ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Volume slider missing on Handel?

I'm having an issue with my volume slider in jQuery - the handle is not showing up despite it working. Any suggestions on how to make the handle visible? The jQuery I have imported: <script src="jquery-3.4.1.min.js"></script> <script ...

Adjust the width of the initial column in the table and ensure it remains noticeable

I am a beginner with bootstrap and I find it extremely useful. I have encountered a problem with a table I am working on. I am trying to set the width of the first column and keep it always visible, but I am having trouble achieving this. I have successful ...

Implementing a Standardized Template for Consistent Design and styling Throughout Website

As I work on building my website, I find myself struggling with some of the intricacies. The homepage is set up with a navbar and header, along with several pages that can be easily navigated to. While everything seems to be functioning properly, upon ins ...