Incorrect enumeration using CSS counters

Can you help me figure out why the numbering of sections is incorrect in this CSS code snippet (http://jsfiddle.net/75MHS/)? When I nest h3 and h4 inside div elements, the chapter numbers and section numbers are always off by one. However, if I remove the div containers, the numbering is correct.

<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
h3 {
  counter-increment: chapter;
  counter-reset: section;
}
h3:before {
  content: "Chapter " counter(chapter) " ";
}
h4 {
  counter-increment: section;
}
h4:before {
  content: counter(section) " ";
}
</style>
</head>
<body>
<!-- wrong counter -->
<div><h3>dddd</h3></div>
<div><h4>dddd</h4></div>
<div><h4>dddd</h4></div>
<div><h3>dddd</h3></div>
<div><h4>dddd</h4></div>
<div><h4>dddd</h4></div>

<!-- correct counter -->
<!--
<h3>dddd</h3>
<h4>dddd</h4>
<h4>dddd</h4>
<h3>dddd</h3>
<h4>dddd</h4>
<h4>dddd</h4>
-->
</body>
</html>

Answer №1

The reason why the functionality works properly in the second section (without the use of divs) but not in the first section is due to the scope of the counter. As mentioned by the W3C:

The scope of a counter begins at the initial element in the document that contains a 'counter-reset' for that counter and encompasses the element's descendants and its subsequent siblings along with their descendants.

In the latter part of the HTML, the h3s and h4s are siblings, hence, the counter-reset set on the h3 applies to the subsequent h4 siblings. Whereas, in the first section of the HTML, the h4s are neither descendants nor siblings of the h3s, resulting in the counter-reset not affecting them as they are out of scope.

Another important aspect is that if counter-reset is not defined within a particular scope, it defaults to a value of 0 each time the counter is counter-incremented or referenced in a content rule. This explains why the first part of the HTML displays all 1s:

If 'counter-increment' or 'content' on an element or pseudo-element refers to a counter that is not in the scope of any 'counter-reset', implementations should behave as though a 'counter-reset' had reset the counter to 0 on that element or pseudo-element.


If you need to enclose elements within divs, I would recommend:

  1. Define a counter-reset for the chapters counter on the body, so it doesn't default to 0 each time counter-increment is used.

  2. Either nest the h4s under their parent h3s (although not ideal) or position them as siblings to ensure they fall within the correct scope.


New HTML:

<div>
    <h3>dddd</h3>
    <h4>dddd</h4>
    <h4>dddd</h4>
</div>
<div>
    <h3>dddd</h3>
    <h4>dddd</h4>
    <h4>dddd</h4>
</div>

Addition to CSS:

body {
    counter-reset: chapter;
}

http://jsfiddle.net/myajouri/QpG9d/

Answer №2

Don't overlook the fact that div elements are now included in the DOM tree; you must either address them specifically or delete them altogether.

div {
    counter-increment: chapter;
    counter-reset: section;
}
div:before {
    content: "Chapter " counter(chapter) " ";
}

Answer №3

I have applied a new class to the wrapper to distinguish the div elements.

See the Live Demo Here

Here is the HTML code:

<div class="head"><h3>Title Here</h3></div>
<div class="sub"><h4>Subtitle Here</h4></div>
<div class="sub"><h4>Subtitle Here</h4></div>
<div class="head"><h3>Title Here</h3></div>
<div class="sub"><h4>Subtitle Here</h4></div>
<div class="sub"><h4>Subtitle Here</h4></div>

And here is the CSS code:

div.head {
  counter-increment: chapter;
  counter-reset: section;
}

div.head h3:before {
  content: "Chapter " counter(chapter) " ";
}

div.sub {
  counter-increment: section;
}

div.sub h4:before {
  content: counter(section) " ";
}

Answer №4

The rationale behind this is that counters are "self-nesting," meaning that resetting a counter in a child element or pseudo-element automatically initiates a new instance of the counter." (CSS 2.1, 12.4.1 Nested counters and scope).

Therefore, in the scenario of the "incorrect counter," each div element that contains an h3 element maintains its own counter called chapter, with each h3 incrementing this local counter.

If you wish to group elements using div elements (or section elements), you can structure them like this:

<div class=chapter>
<h3>Title</h3>
<h4>Subheading</h4>
<h4>Subheading</h4>
</div>
<div class=chapter>
<h3>Title</h3>
<h4>Subheading</h4>
<h4>Subheading</h4>
</div>

In this setup, your CSS would target .chapter instead of h3:

.chapter {
  counter-increment: chapter;
  counter-reset: section;
}

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

Using jQuery to make an Ajax post request that will load the current page with additional form data appended to the

Below is the HTML code for my registration form: <form id="registerForm"> <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required> <inp ...

The use of @font-face in CSS seems to be malfunctioning

I am having trouble changing the font in my CSS to what I want it to be. body{ background-color:#a8a7a7; color:#C50909; font-family: main, Calibri; text-align:center; } @font-face{ font-family: main; src: url('fonts/RegencieLight.ttf'); } ...

Manipulating strings within strings with JavaScript

It's been a strange discovery I made while working with JavaScript. Whenever I try to assign a two-word string to a CSS property, like setting the fontFamily property of an HTML element to "Arial Black", it ends up looking something like thi ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

Is there a way to conceal one column in a row and display only the second column from a medium screen to a small screen using Bootstrap 5?

I am currently working on creating a row with two columns, one being the left_bar column and the other a large image. My goal is to display only the large image (column 2) when the screen size changes from medium to small breakpoints, hiding the left_bar c ...

Attempting to eliminate the padding from the unordered list (ul) element within the pop-up box

Upon clicking the chip with chipName="button test IPA", a popup window appears. I am attempting to remove the padding from the ul tag within that popup. The issue I'm facing is that I cannot locate the ul tag in my HTML or JSX code. I have assigned a ...

Is it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

How can I make <p> elements change color when scrolling?

My Goal https://i.sstatic.net/JbdXR.gif I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.o ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Enhance user experience by enabling clickable links in Angular comment sections

Currently, I'm developing an application that allows users to add comments to specific fields. These comments may contain links that need to be clickable. Instead of manually copying and pasting the links into a new tab, I want the ability to simply c ...

What is the reason behind the variation in CSS caused by spaces in HTML markup?

I've come across a particular markup structure that has caught my attention: <!-- .section markup with line breaks and indentation (normal formatted coding) --> <form id="form" name="form"> <div class="section"> <input type ...

To successfully construct the href route, I must transmit data from an id attribute variable to an href attribute

I'm exploring methods to transfer an id variable either within the same tag or from one tag to another. Specifically, I am working on implementing a popup modal that prompts a user to confirm before deleting another user. <a class="deleteUs ...

Unable to properly call a JavaScript file from an HTML file

Executing this simple code with the JavaScript line placed under Script tags will trigger the desired alert message: <!DOCTYPE html> <!-- saved from url=(0014)about:internet --> <html> <body> <script type="text/javascript" > ...

What methods can I use to ensure my HTML/CSS code is compatible with all browsers? It functions properly on Chrome but encounters issues on Safari, Edge, and other

My hosting for the website is with bluehost, and interestingly when viewed on Chrome, everything appears perfect. However, upon switching to Safari, I noticed that the background of the about me section is not black as intended, and the footer seems to be ...

What is the purpose of the c() function in JavaScript?

I recently stumbled upon some interesting JavaScript code in the source of a web page: function fsb329142055() { var b=new Array(57,50,102,50,52,99,50,53,52,56,102,98,102,98,101,102,101,49,53,61,101,99,110,57,111,78,109,54,114,111,56,48,102,38,1 ...

What is the best way to maintain a div centered when the browser window shrinks smaller than the div's dimensions?

Is there a way to keep a div centered and create white space around it when the browser window is resized? I want this effect to happen whether the browser window gets larger or smaller. Currently, when the window size decreases, the left side of the div l ...

Why can't JQuery/javascript's dynamic gallery's images be used as buttons instead of links?

I've been struggling with my online portfolio for several nights as I build my website. Despite exhaustive internet searches, I couldn't quite articulate my problem in words and tried multiple workarounds. To see the issue, please visit the beta ...

Begin anew with Flip.js

Currently, I am incorporating the jquery flip plugin from nnattawat.github.io/flip to establish a card flipping mechanism on my website. I have successfully implemented the method outlined in the documentation to unregister the flip event from the elemen ...

Modifying the appearance of InputText through CSS encapsulation

I'm a newbie to using Blazor and I'm currently experimenting with changing the style of InputText by utilizing css isolation. Interestingly, I've managed to successfully change the style when setting it inline or internally, however, things ...

Tips for utilizing CSS flexbox to create a row of squares that can scale while maintaining their aspect ratios

Struggling with this issue has me on the verge of pulling my hair out. It seems like a simple task, yet I can't seem to achieve perfection. My goal is to create a row of squares that maintain their aspect ratio but scale down in size as their containe ...