What is the best method for choosing all elements located between two specific elements?

If I have the following HTML code, what CSS selector can I use to target all elements between #one and #two without using jQuery?

<p id="one"></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p id="two"></p>

Answer №1

If you're in search of the ~ general sibling combinator, then look no further

#one ~ p:not(#two) {
  color: red;
}

The purpose of the above selector is to target all the p elements that come after #one up to #two, and using :not() pseudo to exclude the final p:

#one ~ p:not(#two) {
    color: red;
}
<p id="one">0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p id="two">6</p>

JSFiddle

Answer №2

When dealing with two sibling elements (meaning they have the same parent), Selectors 3 does not provide a way to target elements between them if the structure of the elements is unknown or subject to change.

Selectors 3 allows you to select elements between two siblings only if one or both of the following conditions are met:

  1. If the positional relationship of the elements in the parent tree is known.

    For instance, if #one is always the first child and #two is always the last child, you can use:

    #one ~ p:not(#two)
    

    or

    #one ~ p:not(:last-child)
    

    If #one is the second child and #two is the fifth child:

    #one ~ p:not(:nth-child(-n+2)):not(:nth-child(n+5))
    

    If #one is the second child and #two is the third last child:

    #one ~ p:not(:nth-child(-n+2)):not(:nth-last-child(-n+3))
    
  2. If the number of elements to be matched is known.

    It is important to note that if the first condition is met, it is preferable to use the techniques mentioned there. This following technique should be a last resort for cases where the first condition is not applicable.

    If there will always be n elements between #one and #two, you can build a list of selectors starting from #one, adding + p to each subsequent selector up to n times.

    For example, if there are only three p elements between #one and #two:

    #one + p,
    #one + p + p,
    #one + p + p + p
    

In Selectors 4, assuming #one and #two are unique in a conforming document, the following selectors are reliable (meaning they work regardless of the structure of elements, even if it changes):

#one ~ p:has(~ #two)

or

#one ~ p:not(#two, #two ~ p)

When using jQuery or other non-CSS contexts where it is supported, utilize :has(); in CSS, use :not() since :has() with the ~ combinator may not be universally supported. Currently, the latter method is functional in Safari, but its availability in other browsers is still uncertain.

Answer №3

    #first ~ :not( #second ~ * ):not( #second )

Selects all elements that are preceded by #first but not preceded by #second and are not #second

A simple yet effective logic to enhance your coding experience

[UPDATE]

For optimal browser compatibility:

    :not(#first) {
      color: black /* color for elements outside of range */
    }
    
    #first~* {
      color: red;
    }
    
    #second~* , #second {
      color: black /* color for elements outside of range */
    }

Answer №4

To separate the elements, wrap them in a div element and assign it an id that can be targeted in the CSS file to style the contents.

<div id="uniqueID">
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</div>

#uniqueID {
    color: blue;
}
<p>1</p>
<div id="uniqueID">
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
</div>
<p>6</p>

Answer №5

Absolutely, it is possible to target elements between two specific elements:

.container {
  display: grid;
  grid-template-columns: 1fr;
}

.base {
  width: 100px;
  height: 50px;
  background: gray;
  border-radius: 8px;
  margin-bottom: 5px;
}

.first, .second {
  background: green;
}

.first ~ :not(.second):not(.second ~ *) {
    background: blue;
}
<div class='container'>
  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base first'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base second'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

  <div class='base'>
  </div>

</div>

https://codepen.io/Sariato-Jinks/pen/rNgdMbM

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 is not appearing on my Node.js server application

The code snippet below is from my node.js server (using express): app.get('/appointment/:id',function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); res.write('<link href="public/css/style.css" rel="st ...

Is there a way to display multiple Bootstrap 5 modals simultaneously without automatically closing the previous ones?

My current project utilizes bootstrap 5.2, which is a departure from the previous version, bootstrap 3. In bootstrap 3, it was possible to open multiple modals on top of each other, creating an overlapping effect. However, in bootstrap 5 and 5.2, the behav ...

Unable to execute a basic opacity transition on a div element

Why isn't the opacity transitioning in Chrome? I only want it to fade in with the 'transitions' class without fading out first. Check out this code sample: http://jsfiddle.net/chovy/t37k3/9/ <div></div> <a href="#" class="s ...

What is the method for activating or deactivating pointer events for a particular section of an element?

Is it feasible to deactivate pointer events for only a portion of an element rather than the entire element? For instance, as shown in the image below.. https://i.sstatic.net/rnS7M.png Perhaps one could utilize another element to cover the specific area ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

What is the functionality of bootstrap colors?

Recently, I've been practicing my skills with Bootstrap, and I'm determined to understand all aspects of the code. However, one thing that's currently puzzling me is the navbar colors. When I apply the navbar-dark class, instead of displayin ...

Is there a way to verify and send notifications when duplicate entries are added to my table?

Whenever a make and model are added using the "add" button, I need to ensure that there are no duplicates. If a duplicate is found, an alert should be displayed, and the entry should not be added to the table. Unfortunately, I have been unable to find a so ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

ChessboardJs: JavaScript Boards Function Properly on Initial Use Only

Update: The page code can be accessed via my page URL. I'm unsure where the issue lies. Your assistance is appreciated. Issue: Initially, when clicking on the chess puzzles page, everything works fine. However, upon re-clicking from the homepage, th ...

the overflow issue with Summernote's dropdown menu

I am currently working on a 2 columns layout within 2 divs that have different margins set. In the left column, I have integrated a bootstrap datetimepicker and summernote. While the datetimepicker dialog overflows outside the internal div, I am wondering ...

How to implement an 8-column layout within a 12-grid bootstrap framework?

Hey guys, so I've been trying to recreate this page with Bootstrap and it's all going smoothly except for this one part. Here is the link I'm referring to: https://i.sstatic.net/0mXMm.png I have 2 questions: Which HTML element should I us ...

What steps can I take to ensure my header image adjusts properly for different screen sizes?

Currently, I am working on creating a website for a friend using an exquisite premium Wordpress theme. Despite having paid for the theme, the designer is unwilling to assist with customization. You can view the site in progress at www.zerocarbonfood.co.uk ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

ChakraUI failing to display on the screen

Exploring Chakra UI in my latest project has been an exciting journey for me. I made sure to install all the necessary dependencies and started importing components from the ChakraUI Docs. Initially, I successfully imported and rendered the button feature ...

Changing the CSS property from "display: none" to "display: block" using JavaScript causes all the div elements to overlap

My issue involves several radio inputs where clicking one should reveal a hidden div containing information. However, when this div appears, it overlaps with the footer instead of staying positioned between the footer and radio input as intended. I am str ...

What is the best way to implement a 'box-shadow-right' that stops at the border?

How can I achieve a seamless shadow effect at the border-right of a small div that matches the shadow of a larger div, without cutting off at the border-bottom of the small div or the border-top of the large div? I am unable to use Z-index due to the compl ...

Centered image

I am working on a website and struggling to center the image on all screen sizes. I attempted the following code:- <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" lang ...

Using jQuery to animate two images simultaneously in opposite directions

Trying to make two images animate using a single function. The issue is that one image needs to animate the left attribute while the other needs to animate the right. Here's what I have so far: $(document).ready(function(){ v ...

Open the overflow div within a table data cell

My goal is to create a drag-and-drop schedule tool similar to Fullcalendar. I have decided to use a table layout with a rectangular div inside each TD cell to represent tasks. <table onDragEnd={dragend}> <tr> <th>0</th> ...

Flex mode allows for responsive row details in ngx-datatable

Having an issue with my ngx datatable row details. Everything works well initially, but when I adjust the browser width, the details don't scale properly with rows and columns. They seem to have a fixed width that was set when the page was first loade ...