Reputation: 572
Background
So I want to style my component and all its children with a text highlight color to be yellow for example. But I am only able to do it if the component returns the text wrapped within the element itself, and won't work with any text wrapped in its child elements or child components.
For instance, this will change the highlight color:
import React from "react";
import { Container, styled } from "@mui/material";
const StyledContainer = styled(Container)(({ theme }) => ({
"::selection": {
backgroundColor: "#ffe20b"
},
}));
function App() {
return <StyledContainer>hello world</StyledContainer>;
}
export default App;
But if I wrap the text in a child element div
the styling won't work.
import React from "react";
import { Container, styled } from "@mui/material";
const StyledContainer = styled(Container)(({ theme }) => ({
"::selection": {
backgroundColor: "#ffe20b"
},
}));
function App() {
return <StyledContainer><div>hello world</div></StyledContainer>;
}
export default App;
Question
How would I be able to recursively set the style throughout my App? Let's say my most-outter element is a <Box></Box>
and it has a class named MuiBox-root
that we can use.
I have tried the following but none worked:
// didn't work
const StyledContainer = styled(Container)(({ theme }) => ({
margin: theme.spacing(0),
".MuiBox-root::selection": {
backgroundColor: "#ffe20b"
},
// the following didn't work either
const StyledContainer = styled(Container)(({ theme }) => ({
margin: theme.spacing(0),
".MuiBox-root > * ::selection": {
backgroundColor: "#ffe20b"
},
If you highlight the displayed two lines of text, you can see that the first line is styled while the second line isn't. Here is the codesandbox link
Upvotes: 2
Views: 788
Reputation: 1248
You can try following it will work for all child elements
const StyledBox = styled(Box)(({ theme }) => ({
"::selection, *::selection": {
backgroundColor: "#ffe20b"
}
}));
Upvotes: 1