CSS 伪类选择器与 Material UI

93

我在很多Material UI代码中看到他们在React的样式组件中使用伪选择器。我想自己试一试,但是我做不到。我不确定我哪里做错了,或者这是否可能。

我正在尝试创建一些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);
3个回答

239

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

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

然后一切都像预期的那样运作


8
"一些内容"。虽然您错过了闭合引号,但无论如何感谢您,您救了我的一天。 - Doongsil
71
对于空的伪元素来说,这同样很重要。即:content: '""' - Eran Goldin
9
在那上面浪费了两个小时。我使用的内容是:“blabla”,但它没有起作用。 ‍♂️ - Aamir Afridi
2
嗯,这个内容浪费了我的时间。 - Second Son
也浪费了几个小时在这上面。我的情况更糟,因为我正在处理的项目中eslint非常严格,而我们不允许使用单引号。对于那些处于相同境地的人,只需在 content 属性之前添加此行:/* eslint quotes: [2, "double", "avoid-escape"] */,因为这将允许字符串使用单引号或双引号,只要字符串包含一个必须进行转义的引号即可。 - Christopher

53

正如@Eran Goldin所说,检查您的content属性的值,并确保它设置为一个字符串""。很有可能,您在做像这样的事情:

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

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

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

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

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

0

无需显式设置高度

上述解决方案需要显式设置高度。如果您希望高度是动态的,可以尝试以下方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接