Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using useState, but I'm looking for a pure CSS solution. If anyone has any insights or suggestions, please share them.

If achieving this with pure CSS is not possible, could we use event handlers with pseudo-selectors instead? Your thoughts on this would be appreciated as well.

You can view the code on Codepen.

.sticky-table tbody tr:hover td,
.auto-number-table tbody tr:hover td {
  background-color: #e0e0e0;
}

Answer №1

To achieve the desired effect, you can utilize the :has() pseudo class, although it may require extensive CSS and is not compatible with Firefox. An example of the markup is provided below. The final CSS rule targets any table row with a specific data-table attribute when hovered over.

table {
  border-collapse:collapse;
  margin-bottom: 1rem;
}

td {
  border: 1px solid lightgray;
  padding-inline: 0.25rem;
}

:has([data-row='1']:hover) [data-row='1'],
:has([data-row='2']:hover) [data-row='2'],
:has([data-row='3']:hover) [data-row='3'] {
  background-color:red;
}
Data table
<table>
  <tr data-row='1'>
    <td>Row</td>
    <td>1</td>
  </tr>
  <tr data-row='2'>
    <td>Row</td>
    <td>2</td>
  </tr>
  <tr data-row='3'>
    <td>Row</td>
    <td>3</td>
  </tr>
</table>

Autonumber table
<table>
  <tr data-row='1'>
    <td>Auto Row</td>
    <td>1</td>
  </tr>
  <tr data-row='2'>
    <td>Auto Row</td>
    <td>2</td>
  </tr>
  <tr data-row='3'>
    <td>Auto Row</td>
    <td>3</td>
  </tr>
</table>

Edited In your example, the autonumber table appears next to the data table. Consider combining them into a single table and using CSS to differentiate the two. This approach eliminates the need for complex CSS or JavaScript to achieve the desired row hover effect. See the example below:

.container {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
}

.sticky-table {
  flex-grow: 1;
  margin-left: 10px;
  border-collapse: collapse;
  table-layout: fixed;
}

.sticky-table td:nth-child(2) {
  background-color: transparent;
}

.sticky-table th:not(:nth-child(2)),
.sticky-table td:not(:nth-child(2)) {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

.sticky-table th {
  position: sticky;
  top: 0;
  z-index: 2;
}

.sticky-table th:nth-child(2) {
  width: 10px;
}

.sticky-table th:not(:nth-child(2)) {
   background-color: #f0f0f0;
}

.sticky-table tbody tr:hover td:not(:nth-child(2)) {
  background-color: #e0e0e0;
}

.sticky-table td:first-child {
  text-align: center;
  width: 30px;
}
<div class="container">
  <table class="sticky-table">
    <thead>
      <tr>
        <th></th>
        <th></th>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td></td>
        <td>Cell 1</td>
        <td>Cell 2</td>
        <td>Cell 3</td>
      </tr>
      <tr>
        <td>2</td>
        <td></td>
        <td>Cell 4</td>
        <td>Cell 5</td>
        <td>Cell 6</td>
      </tr>
    </tbody>
  </table>
</div>

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

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Issue with material-UI Dialog rendering in snapshot test using React-Testing library

function Component(props) { const { approvalValue, handleSubmit, handleDialog, handleChange, handleApprovalChange, value, characterCount, maxCharacterValue, } = props; const { handleOpen, handleClose, open } = handleD ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

What is the most effective way to ensure a user's email address is not already in my database before submitting a form?

Welcome to my first question post. I'm in the process of creating a test where users can sign in and retake it if they wish. However, I'm facing a challenge in checking whether the user's email already exists in my mariaDB database when they ...

Using JQuery or JavaScript to retrieve the HTTP header information of a specified URL

Hey there! I was wondering if it's possible to retrieve the HTTP Header information for a URL using JavaScript? The URL mentioned above points to the current page, but I'm interested in fetching the header details for any given URL (such as ) C ...

Generate Table Rows with Javascript - produces an excess of cells...>>

I am currently in the process of dynamically creating a table, but I am facing an issue with the number of cells being added. The table I am trying to create has a total of 8 columns (Monday to Friday and a total column at the end). You can view my progr ...

Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser. While I successfully retrieve all products using the following code: export async function getAllProducts() { const productData = await client.fe ...

What is the solution for the error message: "[Vue warn]: Error in mounted hook: 'TypeError: document.getElementById(...) is null'" that appears in the <Root> component?

I'm facing an issue with a checkbox in my Vue.js application. Whenever the user checks this checkbox, the data property accepted changes from false to true. My goal is to hide certain HTML elements when accepted = true. I have been attempting to achi ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

Factory not properly updating AngularJS controller

I am facing an issue with two controllers and one factory in my AngularJS application. The first controller sends an http request to a server, receives a string in response, and stores it in the factory. However, the second controller does not update with ...

Exploring the wonders of Html5 Canvas with base64 encoded images

I have a base64 encoded image that looks like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAADwCA...... Is there a way to draw this on a canvas using the encoded image provided above? Does anyone have an example of how to do this? Updated: ...

Managing form values conditionally using react-hook-form

Whenever the manufacturerWatchValue changes, I need to delete the model's value after the form has been initialized. However, the model loses its value during form initialization because the initialized variable is in the dependency list. Therefore, ...

What are your thoughts on the size of a React component being 500 lines long?

Currently, I am in the process of constructing a Table component that includes filters and requires an extensive amount of logic. Additionally, I have incorporated material UI which tends to add multiple lines of code. Despite these elements, I feel that ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Using the click function in React to narrow down the component map

Currently, I'm working on an exciting project and I've encountered a bit of a challenge that has me stumped. I'm using Axios to fetch data, then rendering it with a .map function. After that, I have a click function that should display only ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Can WikiData be accessed by providing a random pageId?

My current project involves creating a Wikipedia Search App with a 'Feel Lucky' button. I have been trying to figure out if it's possible to send a request for Wikidata using a specific pageid, similar to the code below: async function lucky ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

Retrieve the content within a div tag

Hey there, I have a div set up as follows: <div>1+1</div> I'm looking to send this '1+1' value over to my javascript code and calculate it to get '2'. Appreciate any help in advance! ...