Increase the value on the parent element, while displaying the content on the child element

Having some difficulty with the css 'counter-increment' and 'counter-reset' properties. I've successfully implemented them with lists, but struggling when it comes to header tags.

Consider the following structure:

<div id="root">
    <div class="section">
        <h1 class="header">Header</h1>
        
        <div class="section">
            <h2 class="header">Header</h2>
            <!-- can be nested multiple times -->
        </div>
    </div>
    <div class="section">
        <h1 class="header">Header</h1>
        <!-- content -->
    </div>
</div>

I want the header tags to have numbers (counting nested ones too) but having trouble as the headers themselves don't contain the counters directly. Here's what I've tried so far:

#root
{
    /* Reset counter for root */
    counter-reset: section_header;
}

#root .section
{
    /* Increment for each section div as they wrap children */
    counter-increment: section_header;
}

.section .header::before
{
    /* Display the count, but not getting correct value due to scope issue? */
    content: counters(section_header, ".") " ";
}

Any guidance towards a solution would be appreciated!

PS: Testing mainly on Chrome, but encountering issues on other browsers too.

Edit

Desired format is '1.1', '1.2', '1.2.1' etc.. Nested sections should add another layer to the count. Struggling to achieve dynamic multi-layer numbering.

Answer №1

Just wanted to provide an update: I recently came across the MDN example that served as inspiration for this particular markup. While the original example utilized <ol> and <li> tags to contain child elements, it felt somewhat confusing when translating it into your header-based structure with <h_> elements. Despite this challenge, keeping the child elements within their respective headers seemed necessary to achieve the desired outcome. To enhance clarity, I included after elements along with some minimal CSS styling to clearly delineate the end of each element. Hopefully, these additions prove helpful in understanding the structure better.

.section {
  counter-reset: section;                /* Creates a new instance of the
                                            section counter with each ol
                                            element */
  list-style-type: none;
}

.header::before {
  counter-increment: section;            /* Increments only this instance
                                            of the section counter */
  content: counters(section, ".") " ";   /* Combines the values of all instances
                                            of the section counter, separated
                                            by a period */
}

.section{
  font-size: 16px;
  margin: 10px 0;
}
h1::after {
  content: ' (end h1)';
}

h2 {
  margin-left: 10px;
}
h2::after {
  content: ' (end h2)';
}

h3 {
  margin-left: 20px;
}
h3::after {
  content: ' (end h3)';
}
<div id="root">
  <div class="section">
    <h1 class="header">item</h1>          <!-- 1     -->
    <h1 class="header">item               <!-- 2     -->
      <div class="section">
        <h2 class="header">item</h2>      <!-- 2.1   -->
        <h2 class="header">item</h2>      <!-- 2.2   -->
        <h2 class="header">item           <!-- 2.3   -->
          <div class="section">
            <h3 class="header">item</h3>  <!-- 2.3.1 -->
            <h3 class="header">item</h3>  <!-- 2.3.2 -->
          </div>
         </h2>
         <h2 class="header">item 
          <div class="section">
            <h3 class="header">item</h3>  <!-- 2.4.1 -->
            <h3 class="header">item</h3>  <!-- 2.4.2 -->
            <h3 class="header">item</h3>  <!-- 2.4.3 -->
          </div>
        </h2>
        <h2 class="header">item</h2>      <!-- 2.5   -->
      </div>
    </h1>
    <h1 class="header">item</h1>          <!-- 3     -->
    <h1 class="header">item</h1>          <!-- 4     -->
  </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

"After completing the survey form, the User Details form is displayed upon clicking the submit button

In my Quiz, each question loads on a separate page with clickable options. Some questions may have multiple answers, including an "Others" option. At the end of the quiz, users need to fill out a form. Although I've created a survey form, I'm fa ...

How can the backgroundImage css in react admin <Login /> be replaced using Material-UI?

I have been refering to the following resources: Learn about customizing login page background in React-Admin: Explore themes customization in Material-UI: https://material-ui.com/customization/components/ Instead of using a preset background, I want to ...

Leveraging a Django form across multiple web pages

For my most recent project, I am incorporating a straightforward contact form that directs to the URL /email/. I would like to integrate this form onto the homepage as well. In previous projects, I utilized get_context_data when dealing with a page class i ...

What is the process for streaming video (images) to an HTML5 client using C#?

Currently, I am utilizing C# to fetch continuous bitmaps (video) from an ipcamera. These bitmaps are then converted to base64string and sent (JSON) to an HTML5 canvas, which is responsible for rendering the images. During my research, I came across a meth ...

Changing the image's flex-grow property will take precedence over the flex settings of other child

This is the error code I am encountering, where "text1" seems to be overridden <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--mobile friendly--> <meta name="view ...

Post an image to Facebook without using a link

I have a website and I'm looking to share images on Facebook with the click of a button. I've managed to set up image sharing via URL by hosting them on my server. However, I'm curious about other sharing options available. Can images be ...

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

The dynamic php form features a single set of buttons labeled Next and Before for easy navigation

I am in the process of creating a dynamic form using a single PHP file that displays and saves data from an SQL database. I now want to add two buttons, NEXT and BEFORE, but I have been having difficulty getting them to display or navigate to the next/prev ...

How to centrally align the navbar-brand when the navbar is collapsed in Bootstrap 5

Is there a way to align the navbar Brand in the center when the navbar is collapsed, while keeping it on the left or right side when the navbar expands in Bootstrap 5? ...

Excess spacing in image on top of CSS background overlay

While playing around with text scrolling over a fixed background image (similar to parallax scrolling but with no movement in the background), I encountered an issue. There seems to be a small margin or padding (around 5-10px) between the bottom of the upp ...

Is there a way for me to choose multiple checkboxes simultaneously?

I have a dynamically created HTML table with checkboxes added for each row. $.each(data, function(id, value) { rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+' ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

Do HTML attributes that are customized without the data-* prefix considered valid?

When it comes to AngularJS, the data- prefix is an option but not a requirement in their examples. Should I decide to include the data- prefix in my project, and what are the benefits of doing so? Will my HTML still be valid even if I choose not to make u ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

Using JQuery, it is possible to search for elements by one specific class while excluding others

Looking for a way to target elements with a specific class, but only if they don't have another class attached to them. Here is an example: <li class="target-class exclude-class"></li> <li class="target-class exclude-class"></li& ...

Implementing a Vue.js v-bind:style attribute onto a dynamically generated element post-page initialization

Let me start by explaining my current issue and dilemma: I have been tasked with converting an existing JS project into a Vue.js framework. While I could easily solve a particular problem using jQuery, it seems to be posing quite a challenge when it comes ...

Having trouble making the menu stay at the top of the page in IE7

Check out the demo here: http://jsfiddle.net/auMd5/ I'm looking to have the blue menu bar stay fixed to the top of the page as you scroll past it, and then return to its original position when scrolling back up. This functionality works in all brows ...

Using custom fonts in HTML on Bootstrap is causing issues

After struggling with a persistent problem for quite some time, I decided to delete my initial question since I was already utilizing Bootstrap. However, I am facing an issue where my custom fonts are not being loaded even though my main.css and bootstrap. ...