具有material-ui的CSS伪选择器

del*_*lta 3 reactjs material-ui

我在许多材料用户界面代码中看到,他们在反应样式的组件中使用伪选择器。我以为自己会尝试做,但我无法使其正常工作。我不确定自己在做错什么,甚至不确定是否可行。

我正在尝试使一些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);
Run Code Online (Sandbox Code Playgroud)

Nea*_*arl 21

正如@Eran Goldin 所说,检查您的content财产的价值并确保将其设置为 string ""。很可能,你正在做这样的事情:

'&::before': {
  content: '',
  ...
}
Run Code Online (Sandbox Code Playgroud)

content在输出样式表中根本没有设置属性

.makeStyles-content-154:before {
  content: ;
  ...
}
Run Code Online (Sandbox Code Playgroud)

在 Material-UI 样式对象中,字符串的内容是 css 值,包括双引号,修复它只需写

'&::before': {
  content: '""', // "''" will also work.
  ...
}
Run Code Online (Sandbox Code Playgroud)


del*_*lta 8

我发现content属性需要像这样用双引号引起来

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

然后一切都按预期工作

  • 这对于空伪元素也很重要。即 `内容:'""'` (54认同)
  • 浪费了2个小时。我正在使用内容:“blabla”,但它不起作用‍♂️ (7认同)
  • 内容:““一些内容””,您错过了封闭的报价,但无论如何,谢谢,您保存了我的一天。 (3认同)
  • 好吧,内容浪费了我的时间。 (2认同)