Can CSS be used to target HTML elements that come after another regardless of their position in the document?

Is there a way to style any <h1> element(s) that come after an <h2> element using only CSS?

I've searched through countless pages of CSS documentation, trying to figure out if it's possible to target specific elements that appear AFTER other elements, whether they are in the same branch or a different branch of the HTML markup.

It appears that existing selectors and pseudo-classes are limited to identifying elements that are:

  • Siblings
  • Children
  • Descendants

I am looking for relationships beyond these traditional ones:

  • Nieces
  • Nephews
  • Cousins
  • Third cousins twice removed
  • Granduncles
  • And so on...

These elements would logically appear AFTER a specific element in the HTML structure. However, I cannot predict:

  • The exact nature of the relationship
  • How many instances of the desired elements there will be.

Example 1 - Niece
<div>
  <h2>2</h2>
  <div>
    <h1>1</h1>
  </div>
</div>

Example 2 - Cousin
<div>
  <div>
    <h2>2</h2>
  </div>
  <div>
    <h1>1</h1>
  </div>
</div>

Example 3 - Granduncle
<div>
  <div>
    <div>
      <h2>2</h2>
    </div>
  </div>
  <h1>1</h1>
</div>

Answer №1

Is it feasible to pick any/all individual(s) that appear after an element by using only CSS?

Using solely CSS? Yes
Supported browsers? Limited to Safari and newer versions of Chrome

By utilizing the :has() pseudo-class, we can assess descendants without directly targeting them:

:root {
  --good-browser-support: skyblue;
  --emerging-browser-support: coral;
}

.example :has(h2)+ :is(h1, * h1) {
  /* Ancestor to sibling */
  color: var(--emerging-browser-support);
}

.example :has(h2)+* h1 {
  /* Ancestor to descendant */
  color: var(--emerging-browser-support);
}

.example h2+h1 {
  /* Subsequent siblings */
  color: var(--good-browser-support);
}

.example h2+* h1 {
  /* Nieces */
  color: var(--good-browser-support);
}
Example 1 - Niece
<div class="example">
  <h2>2</h2>
  <div>
    <h1>1</h1>
  </div>
</div>
Example 2 - Cousin
<div class="example">
  <div>
    <h2>2</h2>
  </div>
  <div>
    <h1>1</h1>
  </div>
</div>
Example 3 - Granduncle
<div class="example">
  <div>
    <div>
      <h2>2</h2>
    </div>
  </div>
  <h1>1</h1>
</div>
Example 4 - Uncle
<div class="example">
  <div>
    <h2>2</h2>
  </div>
  <h1>1</h1>
</div>
Example 5 - Non-target: Prior Siblings
<div class="example">
  <h1>1</h1>
  <h2>2</h2>
</div>
Example 6 - Subsequent Siblings
<div class="example">
  <h2>2</h2>
  <h1>1</h1>
</div>
Example 7 - Non-target: Prior Niece
<div class="example">
  <div>
    <h1>1</h1>
  </div>
  <h2>2</h2>
</div>
Example 5 - Non-target: Prior Siblings shared parent
<div class="example">
  <div>
    <h1>1</h1>
    <h2>2</h2>
  </div>
</div>

Simplified version:

:is(.example :has(h2)+ :is(h1, * h1), .example :has(h2)+* h1, .example h2 + h1, .example h2 + * h1) {
  color: magenta;
}
Example 1 - Niece
<div class="example">
  <h2>2</h2>
  <div>
    <h1>1</h1>
  </div>
</div>
Example 2 - Cousin
<div class="example">
  <div>
    <h2>2</h2>
  </div>
  <div>
    <h1>1</h1>
  </div>
</div>
Example 3 - Granduncle
<div class="example">
  <div>
    <div>
      <h2>2</h2>
    </div>
  </div>
  <h1>1</h1>
</div>
Example 4 - Uncle
<div class="example">
  <div>
    <h2>2</h2>
  </div>
  <h1>1</h1>
</div>
Example 5 - Non-target: Prior Siblings
<div class="example">
  <h1>1</h1>
  <h2>2</h2>
</div>
Example 6 - Subsequent Siblings
<div class="example">
  <h2>2</h2>
  <h1>1</h1>
</div>
Example 7 - Non-target: Prior Niece
<div class="example">
  <div>
    <h1>1</h1>
  </div>
  <h2>2</h2>
</div>
Example 5 - Non-target: Prior Siblings shared parent
<div class="example">
  <div>
    <h1>1</h1>
    <h2>2</h2>
  </div>
</div>

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

Having trouble finding two p-col-6 elements side by side in the PrimeNG FlexGrid with Angular?

I have integrated Flex Grid into my Angular7 project. In the initial state, I am able to display two p-col-6 elements side by side without any issues. However, when I try to rearrange them in p-col-12, they no longer align properly. Here is a detailed expl ...

Using JQuery to conceal floated divs

I'm facing an issue that I had resolved the last time I worked on this website. However, I am currently redesigning it to include additional elements, and I am struggling to make the jQuery part function correctly. Essentially, I have an HTML documen ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Adjust the vertical scaling of a container in CSS Grid to maintain aspect ratio similar to an <img>

I am attempting to recreate a demonstration where the house image scales as the viewport height decreases. However, instead of using an <img>, I would like to use a container that also includes absolutely positioned content (unable to provide all the ...

AngularJS: A Step-By-Step Guide to Adding Two Values

Currently, I am utilizing the MEAN stack for my application with AngularJS as the front-end. I have two tables in which I obtained total sum values like 124.10 in the "conversion rate" column. Now, I am looking to calculate the total sum of the "conversion ...

My webpage layout doesn't quite accommodate my content, so I need to adjust it to be more zoom

Why does the page container load bigger than the html/body container in mobile mode, as shown in the photo? Here is my CSS: html { margin-top: 48px; width: 100%; } body { margin: 0; width: 100%; background: var(--bgGray); font-family: Ub ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

What is the best way to add an image using a div in React?

I need assistance getting an image to display as the background in a div element, but it's not working. Below is my code: <div style='background: url("https://images.unsplash.com/photo-1426604966848-d7adac402bff?ixid=M ...

What is the process for incorporating Bootstrap 5 animation into a website?

I'm looking to incorporate animations similar to this example into the background of the page below. However, I'm unsure how to achieve this using Bootstrap 5. The image provided above is what I envision as the background for my HTML page. Any gu ...

Creating JavaScript functions that accept three inputs and perform an operation on them

Apologies in advance if there are any silly mistakes as I am new to Javascript. I want to add "salary", "pension", and "other" together, then display the result in an input field when a button is clicked. Not sure if I have used the correct tags in my cod ...

Struggling to figure out the correct method for aligning calendar using bootstrap-datetimepicker?

Struggling with aligning the calendar correctly under a textbox while using bootstrap-datetimepicker in a form? The positioning seems off, and the calendar icon isn't where it should be. It's not behaving like a simple datetimepicker as shown in ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Issues with Flex layout in Firefox causing functionality errors

My two text inputs are not cooperating with flex properties as expected. They should be positioned like this: https://i.sstatic.net/ZSumb.png However, they are currently positioning like this: https://i.sstatic.net/e430n.png CSS .container{ width ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

Emphasize the checkbox

In my table, I have radio buttons that should turn the neighboring cell green when clicked. Using JQuery, I added a "highlight" class on $.change event to achieve this effect. However, I encountered an issue where some radio buttons load with the "checked ...

The Cascading of Bootstrap Card Designs

Looking for some assistance with my TV Show Searcher project that is based on an API. The functionality is complete, but I'm struggling to get the Bootstrap cards to stack neatly without any empty space between them. I want it to resemble the image ga ...

Sliding Toggle: Panel Revealed with Button Slide

Currently, I am working on implementing a jquery slide tab feature. The functionality is working fine on button click. However, I want the button to stick with the panel and slide along with it. At the moment, the button remains fixed while the panel slide ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Adjust the dropdown width based on the screen's resolution

I recently encountered an issue while implementing a dropdown menu in my React application. Everything was functioning smoothly until I attempted to change the browser resolution through the console. // index.js: <select id="project_type" ...