Utilizing CSS in JS for nested hover styles with Material UI: a step-by-step guide

I am currently utilizing Material UI and in the process of converting regular CSS classes into a JavaScript file.

.nav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.navItem {
    float: left;
    flex: 1;
}

.navLink {
    color: white;
    text-decoration: none;
    display: block;
    font-size: '1 rem';
    font-weight: 500;
    line-height: 1.6;
    letter-spacing: '0.0075em';
    opacity: 1;
    text-transform: 'none';
    min-width: 0;
    padding: 10px;
    margin-left: 10px;
    margin-right: 10px;
}

.navLink-static {
    color: white;
    text-decoration: none;
    display: block;
    font-size: '1rem';
    font-weight: 500;
    line-height: 1.6;
    letter-spacing: '0.0075em';
    opacity: 1;
    text-transform: 'none';
    padding: 10px;
    margin-left: 10px;
    margin-right: 10px;
}

.navLink:hover {
    border-bottom: 2px solid mediumvioletred;
    background: #8DB8DD;
    cursor: pointer;
}

 .navLink:hover > div:hover {
      border-bottom: none;
 }

.navLink.active {
    font-weight: 600;
    border-radius: 0;
    border-color: transparent;
    border-bottom: 3px solid orange;
    padding-bottom: 10px;
}
<ul className={classes.nav}>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/" exact>
            abc
        </NavLink>
    </li>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/def" exact>
            def
        </NavLink>
    </li>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/ghi">
            ghi
        </NavLink>
    </li>
</ul>

How do I convert these CSS styles into a material UI pattern? I am struggling with setting an 'active' state and implementing nested hover styles for elements. Additional documentation on advanced scenarios like this would be greatly helpful.

This is my current progress:


const styles = theme => ({
    nav: {
        listStyleType: 'none',
        margin: 0,
        padding: 0,
        overflow: 'hidden'
    },
    navItem: {
        float: 'left',
        flex: 1
    },
    navLink: {
        color: 'white',
        textDecoration: 'none',
        display: 'block',
        fontSize: '1rem',
        fontWeight: 500,
        lineHeight: 1.6,
        letterSpacing: '0.0075em',
        opacity: 1,
        textTransform: 'none',
        minWidth: 0,
        padding: '10px',
        marginLeft: '10px',
        marginRight: '10px',
        '&:hover': {
            borderBottom: '2px solid mediumvioletred',
            background: '#8DB8DD',
            cursor: 'pointer',
            '&> div &:hover': {
                borderBottom: 'none',
            }
        },
    },
    navLinkStatic: {
        color: 'white',
        textDecoration: 'none',
        display: 'block',
        fontSize: '1rem',
        fontWeight: 500,
        lineHeight: 1.6,
        letterSpacing: '0.0075em',
        opacity: 1,
        textTransform: 'none',
        padding: '10px',
        marginLeft: '10px',
        marginRight: '10px',
    }
});

My attempt to convert .navLink:hover > div:hover {:

Things I have tried.


navLink: {

        '&:hover': {
            borderBottom: '2px solid mediumvioletred',
            background: '#8DB8DD',
            cursor: 'pointer',
            '&> div &:hover': {
                borderBottom: 'none',
            }
        },
        '&:hover > div:hover': {
            borderBottom: 'none'
        }

    },

Any assistance would be welcomed.

Answer №1

Make sure to use the correct syntax:

"&:hover > div:hover": { ... }
.

Check out this example that showcases the proper syntax:

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  navlink: {
    border: "1px solid green",
    fontSize: "16pt",
    "&:hover": {
      backgroundColor: "lightgreen"
    },
    "&:hover > div:hover": {
      backgroundColor: "lightblue"
    }
  }
});
function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <div className={classes.navlink}>
        Hello <div>CodeSandbox</div>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/nested-div-hover-yeri0?fontsize=14

You can also deeply nest with this alternative syntax:

const useStyles = makeStyles({
  navlink: {
    border: "1px solid green",
    fontSize: "16pt",
    "&:hover": {
      backgroundColor: "lightgreen",
      "& > div:hover": {
        backgroundColor: "lightblue"
      }
    }
  }
});

https://codesandbox.io/s/nested-div-hover-3ogmf?fontsize=14

For more information, take a look at the JSS documentation here: https://cssinjs.org/jss-plugin-nested/?v=v10.0.0-alpha.24

See also this related answer:

  • How do you change a style of a child when hovering over a parent using material-ui jss styles

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

Ensuring proper alignment of images and text in HTML when resizing

Trying to show an image and text side by side, I'm using the following code: div.out { background-color: silver; border: 1px solid black; padding: 10px; display: flex; } div.right { order: 1; background-color: white; border: 1px soli ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Creating an object positioned to the right side of a div (div:right) is a matter of using CSS positioning properties

While we are familiar with pseudo-classes like :before and :after, have you ever wondered why there is no nav ul li a:left or :right? Do you think it's achievable? I'm open to using HTML5, CSS3, and JavaScript to make it happen. ...

How you can fix the issue of the "Element not visible" error occurring specifically for one element within the popup

Error Message: "Element Not Visible" when Script Reaches Last Element Despite all attributes being in the same form, an error occurs when the script reaches the last element and displays "element not visible." All elements are enclosed in div tags on the ...

Various text sizes within a nested HTML list structure

I've developed a nested CSS class for an ordered list on my website, but I'm encountering a problem where each list item is appearing in different font sizes even though I have specified the font size. .number_list ol { font:normal 1.2em ...

Header text refuses to cooperate and center itself

Struggling to find the best way to center the "Header" text while keeping the icon in place. I've tried using text-align: center;, but it's not producing the desired results. Could anyone provide guidance on how to achieve this? Thanks. IMG: ...

The CSS child selector seems to be malfunctioning as it is affecting all descendants of the specified type

Struggling with creating a menu containing nested lists. Attempted using a child selector (#menu-novo li:hover > ul) to display only immediate descendants, but all are still showing. Any suggestions or solutions for this issue? #menu-novo-container { ...

What could be causing my API requests to my Vercel hosted API to be interpreted as GET rather than POST? Should I be considering any specific authorization requirements?

I set out to develop a personal portfolio website on Vercel with a combination of Python/Flask for the backend and React for the frontend. During the development phase, I managed to establish communication between my front end component and the backend API ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

The functionality of a Cordova application using Framework 7 CSS can vary across different Android devices

A link is shared for reference showcasing how the progress bar appears on Samsung j2 and other Android devices. Here is the link: [https://i.sstatic.net/C9OpS.jpg](https://i.sstatic.net/C9OpS.jpg) On my personal device, the progress bar is displayed at th ...

React does not play well with the Sendgrid Node.js library

Seeking assistance with integrating node.js to handle email sending on my website. Interested in having the email form immediately send upon submission, rather than using the standard "mailto" action. Utilizing Sendgrid as the email service for API and ser ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

When selecting the top edge in React flow, it will automatically select the bottom

Documentation: Example from documentation: Steps to replicate issue: Drag and drop any node to a different location Select the top edge handle of the moved node Try dragging the edge out and notice that the bottom edge gets selected instead of the top e ...

Steps for developing a floating image transition using CSS and React

Looking to achieve a floating image transition using CSS and React, similar to the Divi theme header images. Check out the example below: enter image description here For more information, visit: ...

ScrollSpy Plugin in JQuery - Implementing automatic vertical text scrolling with dynamic height customization

I have been using this code to display the most recent user comments on my website, where some comments are concise while others are more lengthy. If you inspect the source code, you will notice that the height is set to 90px and overflow is set to hidden ...

Having trouble styling my Aside element correctly

I'm having trouble aligning my aside element on the page. It's not lining up properly with the rest of the content and is overlapping into the header area. How can I resolve this issue? Here's a snapshot of what it currently looks like: ht ...

Updating the status of the parent component in a React/Next.js project

Component "footer": const Footer = () => { const [status, setStatus] = useState<'close' | 'open'>('close') const openImprint = () => { setStatus('open') } const closeImprint = () => { se ...

What causes the width of unrelated cells to change when the contents of colspan'd cells expand in IE7?

Before we delve into the details, I invite you to take a look at this fiddle using IE7. It's quite intricate and not something I want to repeat here. The main issue is that clicking on the red block should display additional information. The top row ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...