skip to Main Content

I can’t figure out how to make :before render in the DOM.

I tried this:

const inline = {
    backgroundColor: "yellow",
    width: "100px",
    height: "30px",
    display: "inline-block",
    position: "relative",
    "&::before": {
        content: '"Good Day"',
        position: "absolute",
        left: "-50px",
        top: "50px",
    },
}

return (
    <p style={style}>
        Lorem ipsum dolor sit amet, <i style={inline}></i>consectetur
        adipiscing elit, sed do<i style={inline}></i> eiusmod tempor
        incididunt ut labore et dolore magna aliqua.
        <i style={inline}></i>
    </p>
)

the styling of the i elements works as expected, except for the :before that is not rendered.

Any tip on how t accomplish this would be much appreciated 🙌

2

Answers


  1. const inline = { /* ... */
        "&::before": { /* ... */ },
    }
    

    The ampersand ("parent selector") is a part of SCSS/SASS/LESS, not the raw CSS properties that React can understand.

    There is no syntax that allows ":before" applied as an inline style, as in this SO answer, nor through JavaScript manipulation as in this SO answer.

    Login or Signup to reply.
  2. Inline css styles do not support pseudo elements (they are not part of the element itself). The only way to apply style to pseudo elements is using css declarations (eg: setting an id and setup a css declaration with #id::before{ }).

    One option for reactjs components is to use an explicit tag that works like :before (or :after) pseudo element, adding it to the start or end of the element content. Eg:

    const inline = {
        backgroundColor: "yellow",
        width: "100px",
        height: "30px",
        display: "inline-block",
        position: "relative",
    }
    
    const before = {
            position: "absolute",
            left: "-50px",
            top: "50px",
    }
    
    return (
        <p style={style}>
            Lorem ipsum dolor sit amet, <i style={inline}></i>consectetur
            adipiscing elit, sed do<i style={inline}></i> eiusmod tempor
            incididunt ut labore et dolore magna aliqua.
            <i style={inline}><div style={before}>"Good Day"</div>Content</i>
        </p>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search