Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

javascript - Cant override styles of nested Material UI components

I am using the card and cardContent component of material ui. I have both in functional components and am trying to override the root style of each. however, I cant figure out how to modify the css of the cardContent component. It seems like that by modifying the root style of card. it wont let me modify the root style of cardcomponent. instead my css shows up in the inspector as being in

.jss14 {
    height: 100%;
    display: flex;
    padding: 0;
    flex-direction: column;
    justify-content: space-between;
}

rather than being in the .MuiCardContent-root

Is there something i am missing with using makeStyles?

my attempt

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

import CardContent from "@material-ui/core/CardContent"

const useStyles = makeStyles({
  root: {
    display: "flex",
    justifyContent: "space-between",
    flexDirection: "column",
    height: "100%",
    padding: 0,
  },
})

export default function AccountCardContent(props) {
  const classes = useStyles()

  return <CardContent className={classes.root}> {props.children}</CardContent>
}

import React from "react"
import { makeStyles } from "@material-ui/core/styles"
import Card from "@material-ui/core/Card"

import AccountCardContent from "../AccountCardContent"

const useStyles = makeStyles({
  root: {
    width: "324px",
    height: "194px",
    borderRadius: "8px",
  },
})

export default function AccountCard({ icon, title, description, onClick }) {
  const classes = useStyles()

  return (
    <Card className={classes.root} onClick={onClick}>
      <AccountCardContent>asdf</AccountCardContent>
    </Card>
  )
}

question from:https://stackoverflow.com/questions/65661586/cant-override-styles-of-nested-material-ui-components

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is correct for the most part and your problem is not related to MUI or React, but CSS specificity. You are trying to overwrite

.MuiCardContent-root:last-child

and the added pseudo class results in a higher specificity than your .jss14 (makeStyles-root-14 in development) class. Ideally you always mimic the selector you are trying to overwrite, in this case:

  root: {
    // other styles
    "&:last-child": {
      paddingBottom: 0
    }
  }

and in case of doubt, you can simply increase specificity step by step by adding additional & to your selector until it works:

  root: {
    // other styles
    "&&": {
      paddingBottom: 0
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...