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

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Using Ajax.ActionLink to pass a parameter in JavaScript

When I call a controller in this manner: @Ajax.ActionLink("Clients", "ClientAccountsPartialView", new { entityCode = -1, taxNumber = -1, country = 1, ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Altering the value of a form upon submission

Struggling with Javascript to update an input value before submitting and storing it in a MySQL table, I encounter the issue of getting a blank row in the database. The code snippet causing this problem looks like this: document.getElementsByName('w ...

The mobile devices do not display minuscule text when rendering the React responsive UI

Recently, I decided to experiment with the responsive drawer feature of React Material UI. To try it out, you can access the online demo through the Code Sandbox link provided in the official documentation. To begin my testing, I copied and pasted the cod ...

JavaScript for loop similar to Python'sIn JavaScript, the

As someone who is new to programming, I primarily use Python but have now encountered a situation where I need to work with JavaScript for a project utilizing Phonegap. The query retrieved from the server looks like this: [["CompanyName", "lat", "long", ...

Access model information from a controller with the help of Next.js and Sequelize

I'm currently working on a project involving Vue.js as my frontend and Next.js as my backend. While everything seems to be running smoothly, I am facing an issue with retrieving my model data back to my controller... Additional details: I have utili ...

WordPress REST API - Issue with New Category returning undefined, yet still able to be accessed

Currently, I am utilizing the WordPress REST API and have successfully created a new category. However, when making queries to the API, it is returning undefined for that particular category. Upon visiting: /wp-json/wp/v2/categories, category 17 does not ...

Tips for incorporating a variable into an action link for HTML and Flask

I am completely new to using Flask and HTML. Currently, I am working on developing a user management tool that includes buttons to perform various actions within Flask. One of the functionalities I am trying to implement is a button that allows users to ...

Error: Unbalanced parentheses detected in the argument list at file path C:UsersgajjaOneDriveDesktopuser_loginviewsupdate.ejs during ejs compilation

When I try to update, instead of showing the form fill field, an error pops up. Can someone assist me with this? <!DOCTYPE html> <html> <head> <title>Form Data</title> </head> <body> <h1>Form Dat ...

Ways to ensure that ng-view stays idle until an XHR response is received

Is there a way to make the ng-view wait for an xhr request? I have two controllers set up for a routed ng-view - the first one loads perfectly, but the second one doesn't render properly because the xhr response is happening after partial.html has bee ...

Despite importing jQuery, the variable '$' cannot be located

Whenever I try to click the button labeled test, it doesn't do anything. However, an error message appears in the console debug indicating: Error: Unable to locate variable '$'. I suspect this might be a jQuery issue, even though I' ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Determining if a method's timeout has been triggered while running on a periodic basis in JavaScript

Within my JavaScript code, I have implemented a method that runs every 5 minutes. However, after 15 minutes, I want to stop this method from executing. var tChk ; tChk = setInterval("test()", 5*60*1000); setTimeout("timeOut(tChk)", 15*60*1000); // 15 mins ...

Installing global confusion with NPM

npm install css-sprite --save npm install css-sprite -g I'm curious about the significance of these two commands. I understand that "-g" makes it global, but why is that important? And what does "--save" do exactly? ...

Is it possible to use mapDispatchToProps in Redux without mapStateToProps?

As I dissect Redux' todo example to gain a deeper understanding, I came across the concept of mapDispatchToProps. This feature allows you to map dispatch actions as props, which led me to consider rewriting addTodo.js by incorporating mapDispatchToPro ...

Can JavaScript be used to save data to a file on a disk?

As a beginner to intermediate programmer exploring AJAX, I was intrigued while learning about JavaScript. It caught my attention that many examples I have come across incorporate PHP for this task. While some may say 'I'm going about it the wrong ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

Even though I am aware that the variable AJAX is attempting to return is not empty, it is still returning 'undefined'

I wrote a basic PHP script that retrieves information from a database and stores it in a multidimensional array: <?php //PHP code to fetch data from DB error_reporting(E_ALL); $db = new mysqli("localhost","root","pass", "Media") ...