Modify the color of every x number of rows on an HTML table

Is it possible to change row colors in a table every x rows, instead of every single row?

For example, here is what the alternating rows could look like when changing every 2 rows: JSFiddle

The structure of the HTML table would be something similar to this:

<table>
    ...
    <tr>
        <td>content</td>
        <td>more content</td>
    </tr>
    ...
</table>

In my current solution, I am using a class for the tr's that should be altered. However, I am looking for a more general approach, possibly utilizing the nth-child selector or a similar method.

Does anyone know of an easy way to achieve this, allowing for variable intervals between altering rows (e.g. every 2 rows, 3 rows, 4 rows, etc.)? Ideally, I would prefer not to manually add class names as the table may be created dynamically and modifying the code might not be feasible.

Answer №1

To set different colors using nth-child, follow this pattern:

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

If you need more than two options, use the formula (an + b) where a is the cycle size, n is a counter starting from 0, and b is an offset value. For example, to assign background colors to tr elements at every multiple of 3:

tr:nth-child(3n+0) {background:#999;}
tr:nth-child(3n+1) {background:#CCC;}
tr:nth-child(3n+2) {background:#FFF;}

Answer №2

Using the nth-child selector is the correct approach here. To target specific rows, consider grouping them in sets of 4:

tr:nth-child(4n+1), tr:nth-child(4n+2) {
    background-color: yellow;
    /* You may also apply additional styles */
}

Answer №3

An Illustration of the Code Above

tr:nth-child(4n+1), tr:nth-child(4n+2) { 
    background-color: gray;
}

4n+1 when n = 0: 4 * 0 + 1 = 1
4n+1 when n = 1: 4 * 1 + 1 = 5
4n+1 when n = 2: 4 * 2 + 1 = 9
4n+1 when n = 3: 4 * 3 + 1 = 13
4n+1 when n = 4: 4 * 4 + 1 = 17
4n+1 when n = 5: 4 * 5 + 1 = 21

The same logic applies to 4n+2:

4n+2 when n = 0: 4 * 0 + 2 = 2
4n+2 when n = 1: 4 * 1 + 2 = 6
4n+2 when n = 2: 4 * 2 + 2 = 10
4n+2 when n = 3: 4 * 3 + 2 = 14
4n+2 when n = 4: 4 * 4 + 2 = 18
4n+2 when n = 5: 4 * 5 + 2 = 22

Keep in mind that n always begins at 0 as a default value.

Answer №4

To target specific rows using the CSS nth-child selector, you can define a custom expression like this:

tr:nth-child(an+b) {    //adjust 'a' and 'b' based on your needs
    background-color: #AAA;
}

See it in action here

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

Tips for updating WordPress without changes appearing live right away

I want to quickly and easily make CSS changes to a WordPress website without doing it live. Is there a way to make these changes locally and then upload them? What is your recommendation? Some people have mentioned that making changes locally can be diffi ...

What is the best way to implement a CSS rule that is influenced by the number of siblings present within an element?

Is there a way to style an element differently based on the number of subelements it contains? <div class="wrapper"> <div class="element" /> </div> or... <div class="wrapper"> <div class="element" /> <div class="el ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

Misalignment of Font-awesome icons in the footer section

I've implemented a footer on my website. My goal is to have the icons centered both vertically and horizontally, with the colored area: Always positioned at the bottom of the screen No taller than the icons themselves Here's the code snippet: ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

Adding the text-success class to a Bootstrap 5 table row with zebra striping does not produce any noticeable change

I am encountering an issue with a Bootstrap 5 table that has the class table-striped. When a user clicks on a row, I have implemented some jQuery code to toggle the class text-success on the row for highlighting/unhighlighting purposes. The highlighting f ...

Utilizing Javascript and CSS for horizontal alignment from left to right

I have a JavaScript function that generates a list of store locations and creates a DIV beneath the map. Currently, the items are displayed top to bottom on the page. However, I would like to change the layout so that the items are shown as 3 in a row fro ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Utilizing the map function to display elements from a sub array

I'm struggling to print out the comments using the map function in this code: class Postcomment2 extends React.Component { uploadcomment = () => { return this.props.post.comments.map((comment) => { return <div>{comment["comment"]}< ...

I find it curious that I need to include the bootstrap link in the body of the HTML file rather than in the head, unlike the bootstrap

Check out the Bootstrap documentation here which states that we should add the link at the end of the body just before its closing tag. As a newcomer, I've noticed linking being done in the head section for non-bootstrap codes, leading me to feel a bi ...

Using PHP to swap out HTML elements

I need a solution to display text with HTML tags as plain text, without the browser interpreting them. I want the output to be similar to how HTML code viewers render it. For example: replacing <div> with <span><</span><span>d&l ...

What is the best way to achieve maximum clarity in a div element while adjusting opacity?

Is there a way to have a div with an opacity of 40%, but make the text inside the div show with an opacity of 100%? #box { Background-color:#000; Opacity:40%; } ...

Avoid shifting focus to each form control when the tab key is activated

I have a form where users need to be able to delete and add items using the keyboard. Typically, users use the tab key to move focus from one element to another. However, when pressing the tab key in this form, the focus only shifts to textboxes and not t ...

What is the best way to stack div elements one after the other?

I am a complete beginner in HTML and I have a project for my web design class about a movie. http://jsfiddle.net/Lbo1ftu9/ <div id="footer"> <a href="D:/MOVIE REPORT/akira.htm" title="GO BACK?"><img src="D:/IMAGES/goback.gif"> My code ...

Develop and arrange badge components using Material UI

I'm new to material ui and I want to design colored rounded squares with a letter inside placed on a card component, similar to the image below. https://i.stack.imgur.com/fmdi4.png As shown in the example, the colored square with "A" acts as a badge ...

Designing the appearance of a jQuery UI range slider

I recently delved into the world of jQuery UI for the first time, and let me tell you, it's been quite the challenge. I've been attempting to create a slider that looks like this: https://i.sstatic.net/YZ3gM.png However, I'm struggling to c ...

Arranging data points into one concise column

Important Note: The code above has been automatically generated by JavaServer Faces. I am working with the following code snippet: <span style="display: block;"> <input checked="checked" type="checkbox">ID <select size="1" &g ...

Creating several divs with an image tag within each div individually using Jade HTML pre-processor

Check out the code snippet below: <div id="cubeSpinner"> <div class="face one"> <img src="/images/Windows%20Logo.jpg" class=""> </div> <div class="face two"> <img src="/images/Turtle.jpg" class ...

Using Selenium in Java to extract text from an h1 tag

Although I am familiar with the method .getAttribute("innerHTML") for retrieving the value of a h1 tag, my HTML structure is a bit different: https://i.sstatic.net/RVaMM.png While I am able to locate the h1 tag, I am facing difficulty in accessing its inn ...

Ways to add more spacing between list items without affecting the position of the bottom div

I'm attempting to achieve a layout similar to an Instagram post, where the list expands but does not push the footer down. In my case, adding margin-bottom to the comment class affects the height of the <div class="post-details-container" ...