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

Adjust the height of the drawer in material-ui

In my current project using react and material-ui, I am facing a simple issue that has me stumped. I am trying to create a drawer with a specific height so that it does not overlap the app bar when opened. Unfortunately, there is no built-in parameter in ...

The content within the iframe is not properly sized

I'm facing a challenge with an iframe that has a fixed height of 1000px which I am unable to adjust. I would like the content to fit within the iframe. As a CSS novice, I need some guidance on how to achieve this. Thank you! <iframe style="height: ...

Need to update various form fields at once with jquery?

There is a form with fields for firstname, lastname, email, country, along with edit icon and submit/cancel buttons. When the user clicks on the edit icon in the top right corner, all values will be displayed in textboxes and the country will be shown in ...

I am experiencing some unwanted movement of divs when I hide one element and show another. Is there a way to prevent this from happening

My webpage features a dynamic div that transforms into another div upon clicking a button. Although both divs share similar properties, clicking the button causes some elements to shift unexpectedly. Strangely enough, when the height of the replacing div i ...

I'm struggling to locate the space that should be between these elements

After accidentally starting in quirks mode without declaring a doctype, I realized my mistake and corrected it by declaring a doctype. However, there is a persistent issue with a space between .car-box-img and car-box that I can't seem to locate in t ...

Is it possible to convert HTML to PDF on the server?

A PDF file is being created from an HTML file using the princexml pdf converter package. The data for the HTML file is provided by the server. In the browser, jQuery is used to generate the input string (HTML code) for creating the PDF. Once the input stri ...

Enhancing productivity with a more streamlined process for creating a responsive website design through the optimization of

I recently had the task of placing two images in a band on a webpage and ensuring they were responsive to different screen sizes. Image 'a' represented a circular logo, while image 'b' was a rectangular logo. The red band served as the ...

Adjust the colors of the borders upon clicking the button

Hello, I'm attempting to create a function where clicking on one button changes its border color to blue and changes the border color of all other buttons to orange. However, I'm encountering an issue where the border color for the other buttons ...

Modify button behavior on click after the initial press

Struggling to make this work the way I want. I have a button that should execute Javascript function A when clicked, and in function A, I need to change the onclick attribute to function B. This way, on the second tap of the button, it will trigger functio ...

Is it possible to prioritize CSS selectors in a specific sequence?

I possess a pair of div elements: div class="one two three" div class="three two one" Is it probable to formulate a CSS regulation that exclusively focuses on ".one.two.three" and does not encompass ".three.two.one" ? ...

Utilizing a jQuery plugin for input file validation

This code is functioning properly, however the file field is not being validated. All input fields are successfully validated by this plugin except for the file type field. I believe there may be something missing in my implementation, so please help me de ...

Tips for using jQuery to add or append a class to the final li element

I am currently struggling to understand why the last child of the li element is not being inserted into the last li. This module functions as a treeview, and my main objective is to add a class to the last li. Let me demonstrate with some sample code and ...

Conceal the initial modal beneath the overlay when the second modal is activated

I have a situation where I am using a modal that contains a button to trigger a second modal. The issue is that the overlay of the second modal does not hide the first modal, it simply darkens the background. How can I make the overlay of the second modal ...

"Comparison: Utilizing HTML5 Video Player with IE8 Embed Fallback versus Implementing Fixed

This dilemma has me at my wit's end. In an HTML5 Video element, I've included an mp4, ogg, and an embedded mp4 fallback. However, on the embed fallback in IE8, all my attempts to position the fixed element (#fixed) above it with z-indexing have f ...

The forecast button seems to be malfunctioning. Each time I attempt to click on it, a message pops up saying, "The server failed to comprehend the request sent by the browser (or proxy)."

Even though I provided all the necessary code, including the Flask app, predictionmodel.py, and HTML code, I am still encountering an error when running it locally after clicking submit. The browser (or proxy) sent a request that this server could not un ...

Let's talk about the CSS properties for centering content and automatically

I've been struggling with getting my navbar to center and adjust its width based on the content inside. Can anyone help me with this? <nav> <ul id="menu" class="black"> <li><a href="index.html">Home</a></l ...

Using AJAX to send data with a POST request in Django may not function properly

Let me preface by saying I have searched for solutions online, but none of them seem to address my specific issue (mainly because they use outdated methods like Jason). I am currently working on a Django project and trying to implement ajax for a particul ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

Creating Images that appear optimized on smaller screens - the art of responsive design!

Currently, I am in the process of working on this test page located at the following link: While the page appears fine on my laptop screen, it is displaying poorly on my phone's browser. The images, in particular, appear disorganized and messy. Coul ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...