nth-child selector causing tbody element to break

I have a code snippet that should alternate row colors between yellow and red. It works perfectly without using the <tbody> tags. However, when I include the <tbody> tags in my code, the layout breaks. It seems to restart with yellow at every new <tbody> block.

Unfortunately, I need to keep the HTML structure as is with the <tbody> tags. Is there a CSS workaround for this issue?

Answer №1

Take a look at this link to see if it fits your needs.

Include the following CSS:

tbody:nth-child(even) tr:nth-child(odd) {
    background-color: red;
}

tbody:nth-child(even) tr:nth-child(even) {
    background-color: yellow;
}

Answer №2

Instead of targeting the nth-child selectors in relation to the table element, disregarding the tbody, it is suggested to target them in relation to each tbody. This approach provides more flexibility and control over styling.

The code snippet below caters to your current HTML structure, assuming there is an odd number of rows in the first tbody. If this changes to an even number, adjustments in the selectors will be required.

tbody:nth-child(odd) tr:nth-child(odd) {
  background-color: yellow;
}

tbody:nth-child(odd) tr:nth-child(even) {
  background-color: red;
}

tbody:nth-child(even) tr:nth-child(odd) {
  background-color: red;
}
tbody:nth-child(even) tr:nth-child(even) {
  background-color: yellow;
}

table {
  width: 100%;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  border-spacing: 0px;
  border-width: 1px;
  border-right-style: dotted;
  border-bottom-style: dotted;
  border-color: green;
}

td {
  padding: 10px;
}

.left {
  min-width: 160px;
  text-align: left;
  padding-left: 10px;
  -webkit-touch-callout: none;
}

.middle {
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.right {
  min-width: 160px;
  text-align: right;
  padding-right: 10px;
}

.boldtitle {
  color: green;
  font-weight: bold;
  padding: 0px;
  margin: 0px;
}

tbody:nth-child(odd) tr:nth-child(odd) {
  background-color: yellow;
}

tbody:nth-child(odd) tr:nth-child(even) {
  background-color: red;
}

tbody:nth-child(even) tr:nth-child(odd) {
  background-color: red;
}
tbody:nth-child(even) tr:nth-child(even) {
  background-color: yellow;
}

td {
  border-width: 1px;
  border-left-style: dotted;
  border-top-style: dotted;
  border-color: green;
}
<table>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Cars</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">GM</a><span class="link_company">GM & </span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">VW</a><span class="link_company">VW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">BMW</a><span class="link_company">BMW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Citroen</a><span class="link_company">Citroen</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Fruits</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Apple</a><span class="link_company">Apple</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Banana</a><span class="link_company">Banana</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Plump</a><span class="link_company">Plump</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

</table>

Answer №3

To avoid coloring the first tr of each tbody, you can utilize the following selectors:

tr:nth-child(2n+3) {
  background-color: red;
}

tr:nth-child(2n+2) {
  background-color: yellow;
}

table {
  width: 100%;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  border-spacing: 0px;
  border-width: 1px;
  border-right-style: dotted;
  border-bottom-style: dotted;
  border-color: green;
}

td {
  padding: 10px;
}

.left {
  min-width: 160px;
  text-align: left;
  padding-left: 10px;
  -webkit-touch-callout: none;
}

.middle {
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.right {
  min-width: 160px;
  text-align: right;
  padding-right: 10px;
}

.boldtitle {
  color: green;
  font-weight: bold;
  padding: 0px;
  margin: 0px;
}

tr:nth-child(2n+3) {
  background-color: red;
}

tr:nth-child(2n+2) {
  background-color: yellow;
}

td {
  border-width: 1px;
  border-left-style: dotted;
  border-top-style: dotted;
  border-color: green;
}

@media only screen and (min-width:751px) {
  .table_details {
    display: none;
  }
}
<table>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Cars</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">GM</a><span class="link_company">GM & </span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">VW</a><span class="link_company">VW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">BMW</a><span class="link_company">BMW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Citroen</a><span class="link_company">Citroen</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Fruits</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Apple</a><span class="link_company">Apple</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Banana</a><span class="link_company">Banana</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Plump</a><span class="link_company">Plump</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

</table>

Answer №4

To achieve the desired effect, apply similar styling to both tbody and tr elements:

tbody:nth-child(odd) tr:nth-child(even) {
  background-color: red;
}

tbody:nth-child(odd) tr:nth-child(odd) {
  background-color: yellow;
}

tbody:nth-child(even) tr:nth-child(even) {
  background-color: yellow;
}

tbody:nth-child(even) tr:nth-child(odd) {
  background-color: red;
}

View below for the final result:

table {
  width: 100%;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  border-spacing: 0px;
  border-width: 1px;
  border-right-style: dotted;
  border-bottom-style: dotted;
  border-color: green;
}

td {
  padding: 10px;
}

.left {
  min-width: 160px;
  text-align: left;
  padding-left: 10px;
  -webkit-touch-callout: none;
}

.middle {
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.right {
  min-width: 160px;
  text-align: right;
  padding-right: 10px;
}

.boldtitle {
  color: green;
  font-weight: bold;
  padding: 0px;
  margin: 0px;
}

tbody:nth-child(odd) tr:nth-child(even) {
  background-color: red;
}

tbody:nth-child(odd) tr:nth-child(odd) {
  background-color: yellow;
}

tbody:nth-child(even) tr:nth-child(even) {
  background-color: yellow;
}

tbody:nth-child(even) tr:nth-child(odd) {
  background-color: red;
}

td {
  border-width: 1px;
  border-left-style: dotted;
  border-top-style: dotted;
  border-color: green;
}

@media only screen and (min-width:751px) {
  .table_details {
    display: none;
  }
}
<table>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Cars</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">GM</a><span class="link_company">GM & </span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">VW</a><span class="link_company">VW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">BMW</a><span class="link_company">BMW</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Citroen</a><span class="link_company">Citroen</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

  <tbody>
    <tr class="header">
      <td colspan="3" class="left">
        <p class="boldtitle">Fruits</p>
      </td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Apple</a><span class="link_company">Apple</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Banana</a><span class="link_company">Banana</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
    <tr>
      <td class="left"><a class="table_details" href="http://www.example.com">Plump</a><span class="link_company">Plump</span></td>
      <td class="middle">XXXXXXXXXX</td>
      <td class="right">YYYYYYYYYY<br></td>
    </tr>
  </tbody>

</table>

Answer №5

If you're waiting for CSS4 standards to become mainstream, why not try out this simple JavaScript snippet I've crafted? It's vanilla JS, so no need for jQuery - QuerySelector is widely supported from IE8 onwards.

Once activated, it will apply the "even" class to rows within tables (excluding table bodies).

var Tables = document.querySelectorAll("table");//Locate all tables in the document
for (var i = 0; i < Tables.length; i++) {
  var Rows = Tables[i].querySelectorAll("tr");//Find rows in each located table
  for (var j = 0; j < Rows.length; j++) {
    if (j % 2 !== 0) Rows[j].classList.add("even");//If row index is even, add the class
  }
}
/* CSS Styles */
table {
  width: 100%;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  border-spacing: 0px;
  border-width: 1px;
  border-right-style: dotted;
  border-bottom-style: dotted;
  border-color: green;
}

td {
  padding: 10px;
}

.left {
  min-width: 160px;
  text-align: left;
  padding-left: 10px;
  -webkit-touch-callout: none;
}

.middle {
  text-align: center;
  margin-left: auto;
  margin-right: auto;
}

.right {
  min-width: 160px;
  text-align: right;
  padding-right: 10px;
}

.boldtitle {
  color: green;
  font-weight: bold;
  padding: 0px;
  margin: 0px;
}

tr{
  background-color: yellow;
}
tr.even {
  background-color: red;
}

td {
  border-width: 1px;
  border-left-style: dotted;
  border-top-style: dotted;
  border-color: green;
}

@media only screen and (min-width: 751px) {
  .table_details {
    display: none;
  }
}
<table>
  <tbody>
    <!-- Table content goes here-->
  </tbody>
</table>

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

Styling a custom Qt class using a CSS selector

I have developed a custom "Slider" widget as a subclass of QWidget and am looking to customize its appearance using Qt's stylesheets. Is there a way to define this widget to the Qt application so that any styling set in the application stylesheet will ...

Attempting to remove an attribute or property in JavaScript will not yield the desired result

When I try to close the menu after opening it, the inline style won't get removed despite trying different methods. The CSS only has text properties for alignment and the class can-transform contains a media query. That's all the information I h ...

How to easily center text across multiple lines using CSS

Looking for a way to center text horizontally and vertically within a div? I had it all working perfectly with this code snippet from a Stack Overflow post: text-align: center; vertical-align: middle; line-height: 90px; /* set line height to match you ...

Activate the WebDAV feature within the .htaccess file

Can WebDAV be activated through an .htaccess file? I'm experiencing issues with Plesk not recognizing my modified config files that have WebDAV enabled. Is it feasible to enable WebDAV without using an .htaccess file? ...

Leveraging jquery to retrieve the value of a selected element

Why is this code not functioning properly? Here is the HTML snippet: <img src='picture.jpg'> <select name='blah[0]' onchange='changePicture();'> <option value='default.jpg'>Default</option> ...

The AJAX functionality seems to have broken following the switch from php5 to php7

When I initially wrote my code in php5, the index page would make an ajax call to check if $_SESSION['user'] was stored. If a session existed, the user's information would be displayed; otherwise, the page would redirect to the login page. H ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

To add a code snippet to the right side of a paragraph using CSS, place it at the end of the

Is there a way to insert code at the end of each paragraph and have it aligned to the right on the same line as the last sentence? Update: I initially tried using float:right, but encountered an issue with vertically aligning the code with the last line ...

In PHP, you can use the `echo` statement to output an HTML input

Incorporating HTML into PHP using heredoc methodology can sometimes lead to challenges when trying to retrieve user input variables. Attempting to access the input variable with $_GET["input"] may result in an error message indicating an undefined index: ...

How can I dynamically retrieve the width of an image in React as the screen size changes?

I have successfully implemented an image hover effect on my website. When I hover over a certain text, an image appears. The image is responsive, but I am facing an issue where I want the width of the text to be equal to the width of the image. When I resi ...

When the CSS style sheet is not embedded within the HTML document, it fails

I'm facing an issue while trying to apply currency formatting to an HTML table in order to have it display correctly when opened in Excel. Initially, I tried doing this inline and it worked fine, like so: <td style="mso-number-format:$\##&bso ...

Investigate the dynamic form validation using jQuery

I have set up an input field using jQuery. When the button "add a step" is clicked, jQuery will generate the following structure in the div all_steps: <div class="step"> <div class="header_step">Step '+ (x + 1) +' of the Tutoria ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Utilizing HTML input elements for focus and blur events

I'm attempting to style an input text field with a thick blue border when in focus, and then have it revert back to its default border when no longer in focus. Here is how one of my input fields is currently defined: <input onfocus="this.style.bor ...

Covering the full width of the page, the background image

My struggle is with setting a background image to 100% width, as the image ends up getting cut off on half of the screen. The picture becomes wider than my display area. How can I resolve this issue so that the image width adjusts to fit the screen without ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Do matrix filters in IE7 take into account white space sensitivity?

Utilizing CSS transformations, I am reverting to the following Matrix transform specifically for IE7 and IE8. filter:progid:DXImageTransform.Microsoft.Matrix(M11=0.0, M12=0.33, M21=-0.33, M22=0.0,sizingMethod='auto expand') This method function ...

What is the best way to apply a CSS class to my anchor tag using JavaScript?

I have a good grasp of using JavaScript to insert an anchor element into my webpage. For instance, var userName_a = document.createElement('a'); However, I am interested in adding a style name to that same element as well. I attempted the follo ...

Achieving a consistent fixed width for tbody even when scrollbar is present

thead{ width: calc(100% - 17px); display:block; } tbody{ display:block; overflow-y: auto; height:100px; } http://jsfiddle.net/mkgBx/ Is there a way to adjust the width of the tbody element to match that of the thead element plus the scrollbar? Currently ...