material-ui makeStyles: how to style by tag name?

ぐ巨炮叔叔 提交于 2021-02-18 11:47:07

问题


I want to add a rule for all <p> in the current component. I couldn't find information anywhere (material-ui documentation, Stack Overflow, etc.) on how to add CSS rules by tag name.

Is it not supported?

I'm trying to do something like this:

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        'p': {
            margin: 0,
        },
        someClass: {
            fontSize: 14,
        },
    })
);

EDIT:

Using Ryan's solution works, but creates a new problem:

import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core';

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        root: {
            '& p': {
                margin: 0,
            },
        },
        // I want this rule to override the rule above. It's not possible in the current configuration, because `.root p` is more specific than `.title`
        // This problem originates from the fact that I had to nest the rule for `<p>` inside a CSS class
        title: {
            margin: '0 0 16px',
        },
    })
);

export default () => {
    const classes = useStyles({});

    return (
        <div className={classes.root}>
            <p className={classes.title}>My title</p>
            <p>A paragraph</p>
            <p>Another paragraph</p>
        </div>
    );
};

回答1:


Since you want this scoped to your component, you need a class to apply to your component (e.g. classes.root in the example below). Then you can target all p elements within that using & p. If you then need to override the p tag styling for another CSS class within your component, you can use another nested rule to target p tags that also have that class (e.g. classes.title in the example).

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

const useStyles = makeStyles(theme => ({
  root: {
    "& p": {
      margin: 0,
      "&$title": {
        margin: "0 0 16px"
      }
    }
  },
  title: {}
}));
export default function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <p>This paragraph isn't affected.</p>
      <p>This paragraph isn't affected.</p>
      <div className={classes.root}>
        <p className={classes.title}>My title</p>
        <p>A paragraph</p>
        <p>Another paragraph</p>
      </div>
    </div>
  );
}

Related documentation: https://cssinjs.org/jss-plugin-nested?v=v10.1.1#use--to-reference-selector-of-the-parent-rule



来源:https://stackoverflow.com/questions/61345362/material-ui-makestyles-how-to-style-by-tag-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!