Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda