Leveraging CSS to automatically number nested sections

Assume we have an example HTML or XML document structured like this:

<body>
   <section>
      <h1>This should be numbered 1</h1>
      <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
      </section>
      <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
      </section>
   </section>
   <section>
      <h1>This should be numbered 2</h1>
      <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
      </section>
   </section>
</body>

This specific layout is just for demonstration purposes, as the number of child-sections within a section can vary, and sections can be nested to any extent.

The question at hand is whether it's possible to utilize CSS (counters and generated content) to automatically generate the desired section number before each section title.

Previous examples mainly showcase this functionality with nested lists using 'counter-reset' on OL and 'counter-increment' on LI tags. However, in this case, it's essential for the 'section' element to both reset for its child-sections and increment relative to its parent section. Combining these behaviors under one element name seems to pose challenges.

Answer №1

In this scenario, it is recommended to utilize CSS counters.

Improved solution (better). A more versatile approach would involve resetting the counter on the body initially instead of the section:first-child, as well as on any immediate next sibling of the h1.

body,
section h1 + * {
    counter-reset: section 0;
}

Enhanced solution. After receiving feedback in the comments about the limitations of my initial solution, I have revised it. The corrected version below should function correctly regardless of the number of nested or sibling sections.

section:first-child,
section h1 + section {
    counter-reset: section 0;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
<section>
    <h1>This should be numbered 1</h1>
    <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.3</h1>
        <section>
            <h1>This should be numbered 1.3.1</h1>
            <p>blah</p>
        </section>
        <section>
            <h1>This should be numbered 1.3.2</h1>
            <p>blah</p>
        </section>
    </section>
    <section>
        <h1>This should be numbered 1.4</h1>
        <p>blah</p>
    </section>
</section>
<section>
    <h1>This should be numbered 2</h1>
    <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 2.2</h1>
        <p>blah</p>
    </section>
</section>


Original (flawed). There is a tricky aspect in this situation: the counter must increment for every subsequent section. This can be achieved by using the section + section selector:

section {
    counter-reset: section;
}
section + section {
    counter-increment: section;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
<section>
    <h1>This should be numbered 1</h1>
    <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
    </section>
</section>
<section>
    <h1>This should be numbered 2</h1>
    <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
    </section>
</section>

Answer №2

ul{
text-align: center;
}

<ul>
  <li>sample</li>
  <li>text</li>
  <li>here</li>
  <li>List</li>
</ul>  

This code snippet has not been tested yet, but it should function properly.

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

Is there a way to automatically transfer the ID from the first table to the id_position field in the second table upon clicking submit?

I'm dealing with two tables and I need to figure out how to add the id of the first table to the position_id field of the second table upon submitting. My request is done through ajax. The fields for the second table are dynamic, meaning you can keep ...

Looking for assistance with HTML regex (even though I understand it's not the recommended approach)

Before we dive in, let me just say that I'm using this regex to work around a bug while waiting for the server team to address it. The issue is that I'm receiving JSON with unescaped " characters within HTML. I need a regex that can identify the ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Is there a way to adjust the positioning of an image within a <div> element?

I'm attempting to vertically align an image within a horizontal menu bar. My goal is to adjust the padding/margin of the image using inline CSS. However, I've noticed that when I add margin-top or padding-top, it affects the positioning of all m ...

Looking for assistance with CSS selectors for the following structure

I am currently working on locating the anchor element "a" that is nested inside a table with the class name table.ic-table-creditReportProduct table tr. I have attempted to find it, but my attempts have been unsuccessful so far. Any suggestions on where th ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

How to add data to Laravel after successful ajax request

I have a div containing bids: @foreach($bids as $b) <div class="bids notice notice-lg"> <strong>{{$b->user->name}}</strong> is offering <span style="font-size: 18px" class="label label-success">{{$b->bid}} €</span ...

Problem with Jquery Ajax, failing to recognize option values

Hello everyone, please review the code snippet below... $.fn.myajax = function (options) { var defaults = { my_event: "", my_url: "", my_data: "", } var o = {}; var mydata = options.my_data; $.extend(o, default ...

Position the button at the bottom of the page with MUI v5 in a React application

How can I ensure the button is always positioned at the center bottom of the page, regardless of the content height? This is a snippet from my code: const useStyles = makeStyles({ button: { bottom: 0, right: 0, position: "absolute" ...

"Revamp the appearance of the div element upon clicking elsewhere on the

function replace( hide, show ) { document.getElementById(hide).style.display="none"; document.getElementById(show).style.display="flex"; } @import url('https://fonts.googleapis.com/css2?family=Allerta+Stenci ...

Creating visual content on Canvas using JavaScript

Having an issue with stacking multiple images on separate Canvas layers, and they're not drawing on the canvas. Can anyone help me figure out what I'm missing? Thanks CSS .positionCanvas{ position: absolute; left:0; righ ...

Attempting to open and display the contents of a text file (.txt) within a modal dialog box upon clicking a button

I am attempting to develop a modal that will appear when the user clicks on a specific button. The goal is for this modal to showcase text retrieved from a separate file stored on the server. My aim is to show this text within a dialog box modal. So far, ...

Getting the css property scaleX with JQuery is as simple as executing the

I am struggling to print out the properties of a specific div element using jQuery. My goal is to have the different css properties displayed in an information panel on the screen. Currently, I am facing difficulties trying to show scaleX. Here is my curr ...

I'm always puzzled by why my attempts to spell a word in a foreign language with accent symbols somehow result in a strange appearance when it comes to bootstrapping

Hey guys, I'm trying to spell a word in Portuguese and instead of PROGRAMAÇÃO, it's showing up as PROGRAMAÇÃO. It seems like the accent symbols are not being displayed correctly. Any thoughts on how to fix this issue? This is happening ...

When the parent element is already set to justify its content with flexbox, you can ensure equal heights for CSS classes by utilizing

Within my design, I have several rows with 3 columns each. Every column contains a main content section labeled SavedSearchBox-content (with various permutations that affect its height) and a footer labeled SavedSearchBox-footer. To structure this layout, ...

MAC Safari is not registering input fields

I'm experiencing a small issue with a form that has two input fields for indicating time (in the format HH:mm) that are very close together, like this: Here is the HTML code snippet: <label> <span>Hour*</span> <input typ ...

Assertion error: 1 does not match the expected value of 6

I am faced with a challenging test that requires me to write code that will pass successfully. However, no matter what I try, all I get is the following error messages: "Failed asserting that 1 matches expected 6" when I return 6 and "Too few arguments t ...

The value retrieved by JQuery attr remains constant

Hey everyone, I'm having an issue with getting the ID from a custom attribute using jQuery. When I try to debug, I keep getting the same value each time. I have an HTML table that lists posts from a database using PHP, each with its own specific ID. ...