2

Code Sandbox here:

https://codesandbox.io/s/ypx4qpjvpx

Relevant bits:

const styles = theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper
  },

  label: {
    fontWeight: "normal"
  },

  selected: {
    fontWeight: "bold"
  }
});



  <Tabs value={value} onChange={this.handleChange}>
    <Tab
      label="Item One"
      classes={{
        label: classes.label,
        selected: classes.selected
      }}
    />
    <Tab
      label="Item Two"
      classes={{
        label: classes.label,
        selected: classes.selected
      }}
    />
    <Tab
      label="Item Three"
      href="#basic-tabs"
      classes={{
        label: classes.label,
        selected: classes.selected
      }}
    />
  </Tabs>

What I'm trying to do here is I need to override the default font weight style, but on selected, I want it to be bold.

The problem is - these have the same level of specificity, and label appears after selected, so it overrides it.

How would I make selected more specific/achieve what I want without using !important.

dwjohnston
  • 11,163
  • 32
  • 99
  • 194

1 Answers1

1

I think the easiest way is to use the root class instead of label (for the Tab component).

Demo: https://codesandbox.io/s/q3pmn9o7m4
(I added colours to make the changes easier to see.)

<Tab
    label="Item One"
    classes={{
        root: classes.tabRoot,
        selected: classes.selected,
    }}
/>

const styles = theme => ({
    root: {
        flexGrow: 1,
        backgroundColor: theme.palette.background.paper,
    },

    tabRoot: {
        fontWeight: "normal",
        color: "#fff",
    },

    selected: {
        fontWeight: "bold",
        color: "#0ff",
    }
});

A different way: https://codesandbox.io/s/8op0kwxpj

const styles = theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },

  tabRoot: {
    fontWeight: "normal",
    color: "#fff",
    '&$selected': {
      fontWeight: "bold",
      color: "#0ff",
    },
  },

  selected: {},
});
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • 1
    I would point out that that the order of the selectors in the `styles` object matter in this solution: see: https://codesandbox.io/s/9lxoljnpmw – dwjohnston Oct 01 '18 at 22:25
  • There are different ways to do this (that don't rely on the order of object keys), but this situation also happens in native CSS ([for example](https://stackoverflow.com/questions/7371732/why-does-foo-alink-foo-avisited-selector-override-ahover-aactive-s)). Here's a different way (using JSS trickery) inspired by [the source](https://github.com/mui-org/material-ui/blob/8995f085904eb55bcb5861fb6d8a32fbd38d72eb/packages/material-ui/src/Tab/Tab.js#L33): https://codesandbox.io/s/8op0kwxpj – thirtydot Oct 01 '18 at 23:06