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>
  )
}

2 answers

  • answered 2021-01-11 05:23 Ziru Zanrgeiff

    Basically, the Material UI components accepts a classes prop that can be used to override its styles.

    Please check it out here

    So you can this:

    <Card
      classes={{
        root: classes.root, // class name, e.g. `classes-nesting-root-x`
      }}
    >
    

  • answered 2021-01-11 22:11 hotpink

    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
        }
      }