Skip to content
Advertisement

Pseudo element not showing in React on paragraph tag despite using display block

This pseudo element ::after won’t show up in my browser at all. I am using React.js and Material UI makeStyles.

This is the code:

modalTitle: {
    borderBottom: '2px solid red',
    display: 'block',
    margin: '10px 15px',
    padding: '0',
    width: '100px',

    '&::after': {
        background: 'green',
        content: '',
        display: 'block',
        height: '2px',
        width: '2px',
    },
},

Note that the code below modalTitle shows up and works, only the pseudo element doesn’t go through. Any thoughts?

Advertisement

Answer

This is a tricky one. When you use makeStyles, it accepts a styles object (or a function that returns an object). This object has the class names as keys and objects containing attribute-value pairs as values. These values are strings (like "block", "green", or "10px 15px").

The ::before and ::after pseudo-elements in CSS allows us to insert content onto the page. Every pseudo-element must have a CSS content property, without it the default value of content is set to normal/none, and no content is displayed.

The problem with your code is that you add content: '' in your object, but you need to pass an empty string as the CSS value, like this: content: '""'.

Similarly, if you want to insert some text using content you can’t simply add the string, you need to use quotes around the text and pass it as a string:

// ❌ this one doesn't work
{
  content: 'some text',
}

// ✅ this one does work
{
  content: '"some text"',
}

So, you can use the following and it will add the element:

const useStyles = makeStyles({
  modalTitle: {
    borderBottom: '2px solid red',
    display: 'block',
    margin: '10px 15px',
    padding: '0',
    width: '100px',

    '&::after': {
      background: 'green',
      content: '""',
      display: 'block',
      height: '2px',
      width: '2px',
    },
  },
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement