What is the proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it:

table tr,
td {
  border: 1px solid black;
}
tr:nth-child(1) {
  background-color: red;
}
tr:nth-child(2) {
  background-color: blue;
}
<table>
  <tr>
    <td rowspan=2>Section 1</td>
    <td>Data 1a</td>
  </tr>
  <tr>
    <td>Data 1b</td>
  </tr>
  <tr>
    <td rowspan=3>Section 2</td>
    <td>Data 2a</td>
  </tr>
  <tr>
    <td>Data 2b</td>
  </tr>
  <tr>
    <td>Data 2C</td>
  </tr>

I am trying to find a simple CSS solution using nth-child to apply styling, such as background colors, to a group of rows within a "Section" that is defined by row spans.

The current CSS only styles individual table rows based on their position, but I want to target and style multiple rows based on the number of rows spanned by a cell.

In this example, I would like to:

  • Make Section 1, Data 1a, and Data 1b appear in red
  • Style Section 2, Data 2a, Data 2b, and Data 2c with a blue color

If you have any suggestions for achieving this using simple HTML/CSS without relying on JavaScript, please let me know!

Answer №1

Another way to make this function

table tr,
td {
  border: 1px solid black;
}
tr:nth-child(1), tr:nth-child(2){
  background-color: red;
}
tr:nth-child(3),tr:nth-child(4),tr:nth-child(5) {
  background-color: blue;
}*/
<table>
  <tr>
    <td rowspan=2>Section 1</td>
    <td>Data 1a</td>
  </tr>
  <tr>
    <td>Data 1b</td>
  </tr>
  <tr>
    <td rowspan=3>Section 2</td>
    <td>Data 2a</td>
  </tr>
  <tr>
    <td>Data 2b</td>
  </tr>
  <tr>
    <td>Data 2C</td>
  </tr>

Answer №2

The solution that I found to be effective (thanks to @RobG's suggestion) is organizing the group rows into segments using <tbody>. This way, I can easily target each tbody element.

Below is the updated example that demonstrates this concept:

table tr,
td {
  border: 1px solid black;
}
tbody:nth-child(1) {
  background-color: red;
}
tbody:nth-child(2) {
  background-color: blue;
}
<table>
  <tbody>
  <tr>
    <td rowspan=2>Section 1</td>
    <td>Data 1a</td>
  </tr>
  <tr>
    <td>Data 1b</td>
  </tr>
  </tbody>
  <tbody>
  <tr>
    <td rowspan=3>Section 2</td>
    <td>Data 2a</td>
  </tr>
  <tr>
    <td>Data 2b</td>
  </tr>
  <tr>
    <td>Data 2C</td>
  </tr>
  </tbody>

Answer №3

If you opt for simple classes or IDs for your table rows and cells, managing them becomes a breeze. I included the header cells in this example, but even if you switch them back to regular cells, the outcome remains consistent. By assigning appropriate class names to each row, it becomes easier to target them, allowing for seamless addition of <td> tags to red or blue rows which will automatically inherit the correct color, eliminating the need to determine their position.

table tr,
td, th {
  border: 1px solid black;
}
tr.red > td, tr.red > th {
  background-color: red;
}
tr.blue > td, tr.blue > th {
  background-color: blue;
}
<table>
  <tr class="red">
    <th rowspan=2>Section 1</th>
    <td>Data 1a</td>
  </tr>
  
  <tr class="red">
    <td>Data 1b</td>
  </tr>
  
  <tr class="blue">
    <th rowspan=3>Section 2</th>
    <td>Data 2a</td>
  </tr>
  
  <tr class="blue">
    <td>Data 2b</td>
  </tr>
  
  <tr class="blue">
    <td>Data 2C</td>
  </tr>
  
</table>

https://jsfiddle.net/wm0nx4cg/1/

Answer №4

If you prefer not to modify your HTML code, here is a straightforward solution:

tr, td {
    border: 1px solid black;
}

tr, tr + tr  {
    background-color: red;
}

tr + tr + tr {
    background-color: blue;
}
<table>
   <tr>
       <td rowspan=2>Section 1</td>
       <td>Data 1a</td>
   </tr>
   <tr>
       <td>Data 1b</td>
   </tr>
   <tr>
       <td rowspan=3>Section 2</td>
       <td>Data 2a</td>
   </tr>
     <tr>
       <td>Data 2b</td>
   </tr>
   <tr>
       <td>Data 2C</td>
   </tr>
  </table>

Also check out this Fiddle.


If you are open to including tbody elements in your markup, then this option might work for you:

tr, td {
border: 1px solid black;
}

tr  {
background-color: red;
}

tbody + tbody tr {
background-color: blue;
}
<table>
   <tbody>
       <tr>
           <td rowspan=2>Section 1</td>
           <td>Data 1a</td>
       </tr>
       <tr>
           <td>Data 1b</td>
       </tr>
   </tbody>
   <tbody>
       <tr>
           <td rowspan=3>Section 2</td>
           <td>Data 2a</td>
       </tr>
       <tr>
           <td>Data 2b</td>
       </tr>
       <tr>
           <td>Data 2C</td>
       </tr>
   </tbody>
  </table>

Also see this Fiddle.

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

Changing the scroll ball's height using CSS

Can the scrollbar height be adjusted in this section? I've tried using overflow-y:auto, but it seems to start from the header and extend all the way to the bottom. When I scroll, the header moves along with it. Header needs fixing Scrollbar height a ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

Error message: `$injector:modulerr - Angular JS` - Indicates an

Currently, I am trying to delve into the world of Angular JS by taking the codeschool course "Shaping up with angular js". The instructor in the videos emphasizes the importance of wrapping code in function(){}. However, upon attempting to do so, an error ...

Conceal the scrollbar track while displaying the scrollbar thumb

Hey there! I'm looking to customize my scroll bar to have a hidden track like this. Everyone's got their own style, right? ::-webkit-scrollbar{ width: 15px; height: 40px; } ::-webkit-scrollbar-thumb{ background-color: #DBDBDB; borde ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Tips for utilizing CSS to position a semi-circle in the middle of an image

Can CSS create a half circle effect on any image? I want to achieve a half circle effect in an image using CSS. Is this possible or not? ...

Checking the availability of a username by sending an Ajax request every time the user types it may lead to inefficiencies and slower response times. Are there

I have developed a NodeJS authentication application. In this scenario, when a user enters a username, the system will display "username taken" if it is already in use, otherwise it will show "username available". I am interested in understanding the lim ...

Clicking on the icon reveals the current date

I need some help with the input field that displays the calendar date. Currently, I can only click on the input field to show the calendar date. What I actually want is for users to be able to click on a calendar icon to display the calendar date, which sh ...

Implementing dynamic active class changes in a navbar with JavaScript

My goal was to have the navbar change its class to 'active' dynamically when a user clicks on the <li> tag. Can you help me pinpoint where I made a mistake? dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a'). ...

What is causing the issue with CSS properties and media queries not being effective on specific elements?

I have been experimenting with React and SCSS to create a portfolio page. Although I am familiar with these tools, I recently encountered issues where certain style changes were not reflecting in the browser. One specific problem involved styling the head ...

The issue with dynamic sizing in React and Tailwind is that it does not consistently work with arbitrary sizes. Some sizes do not appear properly, causing items to

In this code snippet, I am attempting to create a circle component of dynamically sized using html div and Tailwind CSS w-[diameter] & h-[diameter] attributes in a create-next-app@latest project. However, the circle fails to render properly with certa ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

Incorporating JS objects into HTML: A comprehensive guide

Here is a snippet of code from my JavaScript file: var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick=& ...

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

Extract particular details from my database

I need help creating a table to display all chat messages sent to the server. I have the table set up, but now I want to make it so that when I click on a user's name like 'demo', it will show me all the chat messages sent by that specific u ...