Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  144] [ 7]  / answers: 1 / hits: 13402  / 4 Years ago, tue, april 21, 2020, 12:00:00

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

More From » reactjs

 Answers
9

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


Edit



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


[#4080] Saturday, April 18, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
;