I'm trying to change the background of one div on the hover of another using material ui.
The standard css is:
#a:hover ~ #b {
background: #ccc;
}
This is my attempt in material ui.
const useStyles = makeStyles(theme => ({
a: {
background:'#fff',
},
b: {
background:'#fff'
'&:hover ~ #a': {
background:'#eee'
}
}));
The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. Syntax. Example. CSS.
The majority of styles that are applied to Material-UI components are part of the theme styles. In some cases, you need the ability to style individual components without changing the theme.
By calling useStyles () within the component, you have your classes object. Another important thing to point out is that makeStyles is imported from @material-ui/styles, not @material-ui/core/styles. Most Material-UI components have a CSS API that is specific to the component.
I highly recommend taking a look. The makeStyles hook is the current (V4) “proper” way to create styles for components. The underlying logic is the same as withStyles according to the docs. There’s one less import needed for makeStyles compared to withStyles (not shown in my code below).
$
is the character to use when referencing another rule name ("b" in this case). You can find this documented here. #b
would be the CSS syntax for matching an element with an id of "b".
Below is a working example.
import React from "react";
import ReactDOM from "react-dom";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
a: {
"&:hover ~ $b": {
backgroundColor: "#ccc"
}
},
b: {}
});
function App() {
const classes = useStyles();
return (
<div>
<div className={classes.a}>This is a</div>
<div className={classes.b}>This is b</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With