When choosing a category and the initial three choices, the nth-child and nth-of-type selectors become irrelevant

Within the DOM element #installations, there are multiple children elements, with only one having a class of .selected. My goal is to select this element along with the first 3 remaining elements that do not have the class .selected in order to display only 4 elements total.

The challenge lies in the following expression:

#installations > *:not(.selected):nth-of-type(-n+3), .selected

The issue is that :nth-of-type() ignores the :not() selector and simply selects the first 3 children of #installation. For example, if the HTML looks like this:

<div id="installations">
    <div id="one"/>
    <div id="two"/>
    <div id="three" class="selected"/>
    <div id="four"/>
    <div id="five"/>
</div>

Only "one", "two", and "four" will be selected, excluding "three". This happens because :nth-of-type() has limited options due to the exclusion of the selected element by :not(), resulting in (one, two, four) being chosen. The later part of the selector , .selected then includes the selected element.

If the .selected element is not among the first four elements but instead, let's say, the sixth element, the selection would consist of the first three elements plus the sixth.

To clarify: it is acceptable to select the .selected element along with 3 adjacent elements. However, this also poses difficulties when the .selected element is within the last 3 elements as selecting the next 3 becomes problematic.

Answer №1

In my reply, I explained that pseudo-classes are not processed in order; they are all evaluated simultaneously on each element. You can find more information in this detailed answer.

After some experimentation with your HTML and the criteria for selecting elements, I devised a rather lengthy list of selectors:

/* The first three children will always be selected at a minimum */
#installations > div:nth-child(-n+3),
/* Select .selected if it's not among the first three children */
#installations > div.selected,
/* If .selected is among the first three children, select the fourth */
#installations > div.selected:nth-child(-n+3) ~ div:nth-child(4)

To make this work, one key assumption needs to be made: the selected class will only be applied to a single element at a time.

You must combine all three selectors within the same rule to target the four desired elements. Pay attention to the commas in the code snippet.

Try out an interactive jsFiddle demo (to test the selector with the class in various child elements)


If possible, leveraging JavaScript might provide a simpler solution. For instance, using jQuery and its :lt() selector can streamline things:

// Use this selector to apply styles instead: #installations > div.with-jquery
$('#installations')
    .children('div.selected, div:not(.selected):lt(3)')
    .addClass('with-jquery');

Check out an interactive jsFiddle demo (disregard the JS code in the demo; it's just for interactivity purposes)

Answer №2

If you want to display only specific adjacent sibling items, you can make use of adjacent sibling selectors. Here is a sample code snippet that demonstrates this technique and works well in Safari (although it has not been tested on other browsers). In this example, only the 'Two', 'Three', and 'Four' items will be visible.

<!DOCTYPE html>
<html>
  <head>
    <style>
      .the-list li {display:none;}
      .the-list li.selected {display:block;}
      .the-list li.selected + li {display:block;}
      .the-list li.selected + li + li {display:block;}
    </style>
  </head>
  <body>
    <ol class='the-list'>
      <li>One</li>
      <li class='selected'>Two</li>
      <li>Three</li>
      <li>Four</li>
      <li>Five</li>
      <li>Six</li>
    </ol>
  </body>
</html>

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

Contrasting one-finger scrolling versus dual-finger scrolling on a touch device with IE11

Can you explain the distinction between scrolling using one finger versus two fingers in IE11? I have noticed that I am able to scroll/pan the webpage with just one finger on certain elements, while on other elements, I need to use two fingers on a Micros ...

Tips for maintaining the footer at the bottom of the page regardless of the screen size

In my current project, I am dealing with several web pages. For each page, I have arranged three div tags: Header Body (content) Footer The issue arises when it comes to the body div tag, which houses the main content of a page such as forms and descrip ...

CSS code influencing unintended elements

www.geo-village.com <- Live Example After setting up my main webpage with CSS and PHP files, I noticed an issue with the navigation bar. Despite having a separate PHP and CSS file for the navigation bar items, the Login and Register buttons on the main ...

Shifting Transition for Customer Reviews

I am working on implementing a testimonial slider on my webpage located at . I am trying to make it automatically slide by itself, but have been unsuccessful so far. I would appreciate if you could visit the demo page on my website and help identify what ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

The navigation bar does not show any items

I recently decided to implement the BEM methodology in my application starting with the navbar. However, I encountered a problem where my nav items are not being displayed properly and the hamburger icon is appearing on the desktop version, which is incorr ...

I seem to be having trouble with my dropdown menu, can anyone help me figure out what I might be doing wrong

I'm new to web development and I'm trying to create a dropdown menu. The issue is that when I hover over a specific element, it takes up more space than expected. My goal is for it to appear below the "shop" element. I'm not sure where I&a ...

Employ jQuery to set values for hidden input elements

I'm facing an issue where I need to assign a value to a hidden field on a form that I attach to a div when a button is clicked. Below is the snippet of my HTML code: <div style="margin-bottom:5px" class="comment" data-commentID="<?php echo $c- ...

Application of stroke-linecap in SVG limited to single end only

Can a linecap be added to only one end of a stroke, rather than both ends like in the default sample below? <?xml version="1.0"?> <svg width="120" height="120" viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg"> < ...

Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together. I suspect there may be an error in my JavaScript code. In the original code, I used images in front and an unordered list in the back, but here I have simplified it t ...

Is there a way to incorporate two Bootstrap navbars on a single page that are of varying heights?

Utilizing Bootstrap 3.0 with dual navbars on a single page that adjust in height using the same variable for both .navbar blocks. Despite attempting to incorporate an additional class to alter the height of the initial navbar, it remains unaffected. Check ...

Update the background color of an li element upon clicking

Is there a way to change the background color upon clicking on the li anchors? <div class="text-center row"> <ul class="col-md-12 secondNav"> <li class="navbar-brand nav-item" style="margin-right: 9%"> <a href="#" >& ...

What is the best way to highlight the active link in my sidebar navigation bar when using material design in an Angular application?

<div class="mt-3"> <mat-nav-list> <a mat-list-item class="ml-2" style="font-size:15px;" (click)='paycard.html'> SERVICES </a> <a mat-list-item class="ml-2" style="font-size:15px;" (click ...

Use jQuery to swap out images and witness the image loading in real time

Currently, I am using jQuery to dynamically change images by using the code $('img').attr('src','newUrl'); However, whenever I do this, the image is only displayed once it has completely loaded. Due to my slow internet conne ...

Imitating the Frameset Separator's Actions

The latest HTML5 specification has eliminated the <frameset> element. One useful feature of the <frameset> tag that is hard to replicate without it is: In a frameset, you can adjust the position of the frame divider line with the mouse. Is t ...

Bespoke media queries spanning the entire application

Currently, I am utilizing the angular7 application along with bootstrap 4.2.1. Although Bootstrap provides numerous breakpoints, I only require three specific breakpoints for my project. To achieve this customization, I made modifications in the following ...

A guide on using Beautiful Soup to retrieve all text elements from a specific class

This is my custom code snippet: # -*- coding: utf-8 -*- from time import sleep import requests from bs4 import BeautifulSoup def get_all_coins(): response = requests.get("https://coinmarketcap.com/") soup = BeautifulSoup(response.content, 'ht ...

Navigate through HTML checkboxes using jQuery

I am attempting to use jQuery to create a script that performs the following task. Upon clicking on a paragraph, it will check if a checkbox is selected. If it is, it will wait for a specified amount of time before selecting the next checkbox, and so on. ...

How come the HTML content stored in a Mongodb document in JSON format is showing up as plain text on the webpage?

I am currently working with a mongo database that contains a document including some HTML content. However, when I attempt to display this content on a webpage, it appears as plain text rather than rendered HTML. Here is the JSON snippet showcasing the HTM ...

When running a local server with Node.js, the file index.js cannot be found if it is located one folder above the

I am relatively new to node.js and have encountered an issue while running a local server with index.js located one directory up from index.html. The browser is giving me an error message in this scenario. However, when I run the server with index.js in t ...