使用 MUI 的 CSS 伪选择器

我在许多 MUI 代码中看到,它们在其响应样式组件中使用伪选择器。我想我会尝试自己做,但我不能让它工作。我不知道自己哪里做错了,也不知道这是否可能。

我试图使一些 CSS,将抵消这个元素对固定的标题。

import React from 'react';
import { createStyles, WithStyles, withStyles, Typography } from '@material-ui/core';
import { TypographyProps } from '@material-ui/core/Typography';
import GithubSlugger from 'github-slugger';
import Link from './link';


const styles = () =>
createStyles({
h: {
'&::before': {
content: 'some content',
display: 'block',
height: 60,
marginTop: -60
}
}
});


interface Props extends WithStyles<typeof styles>, TypographyProps {
children: string;
}


const AutolinkHeader = ({ classes, children, variant }: Props) => {
// I have to call new slugger here otherwise on a re-render it will append a 1
const slug = new GithubSlugger().slug(children);


return (
<Link to={`#${slug}`}>
<Typography classes={{ root: classes.h }} id={slug} variant={variant} children={children} />
</Link>
);
};


export default withStyles(styles)(AutolinkHeader);
74831 次浏览

I found out that the content attribute needed to be double quoted like this

const styles = () =>
createStyles({
h: {
'&::before': {
content: '"some content"',
display: 'block',
height: 60,
marginTop: -60
}
}
});

and then everything worked like expected

As @Eran Goldin said, check the value of your content property and make sure it's set to a string "". Odds are, you are doing something like this:

'&::before': {
content: '',
...
}

Which doesn't set the content property at all in the output stylesheet

.makeStyles-content-154:before {
content: ;
...
}

In Material-UI style object, the content of the string is the css value, including the double quote, to fix it simply write

'&::before': {
content: '""', // "''" will also work.
...
}

Without having to explicitly set a height

The above solutions require explicit height. If you want height to be dynamic, you can do something like this:

  &::after {
content: '_'; // Any character can go here
visibility: hidden;
}