reactjs CSS pseudo selectors with Material UI

xiozqbni  于 2023-05-22  发布在  React
关注(0)|答案(3)|浏览(118)

我在很多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);
nhaq1z21

nhaq1z211#

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

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

然后一切都像预期的那样

t9aqgxwy

t9aqgxwy2#

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

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

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

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

在Material-UI样式对象中,字符串的内容是css值,* 包括 * 双引号,只需将其修改为

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

oxiaedzo3#

无需显式设置高度

上述解决方案需要明确的高度。如果你想让高度动态变化,你可以这样做:

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

相关问题