Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
Material UI styled() utility - How to recursively change highlighted text background color

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can try following it will work for all child elements

const StyledBox = styled(Box)(({ theme }) => ({
  "::selection, *::selection": {
    backgroundColor: "#ffe20b"
  }
}));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!