What could be causing my Styled Components not to display the :before and :after pseudo elements?

When attempting to use the content property in a :before or :after pseudo element, I am encountering a rendering issue. Here is a simplified version of the component:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Container = styled.div`
  display: block;
  padding: 1rem;
`;

const Foo = styled.p`
  &:before {
    content: '\201C';
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 4.25rem;
  }

  &:after {
    content: '\201D';
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 2.625rem;
  }

  font-weight: bold;
`;

function Test({ txt }) {
  return (
    <Container>
      <Foo>{txt}</Foo>
    </Container>
  );
}

Test.propTypes = {
    txt: PropTypes.string.isRequired,
};

export default Test;

However, nothing appears to be rendered. Referring to this answer from How to render pseudo before content dynamically in styled-component, I attempted:

const Foo = styled.p`
  &:before {
    content: '\201C';
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 4.25rem;
  }

  &:after {
    content: '\201D';
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 2.625rem;
  }

  font-weight: bold;
`;

Another recommendation from this answer suggests using double colons as shown in Can anyone tell me why before not working on styled components?:

const Foo = styled.p`
  &::before {
    content: '\201C';
    display: block;
    font-size: 4rem;
    font-weight: 700;
    height: 4.25rem;
  }

  &::after {
    content: '\201D';
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 2.625rem;
  }

  font-weight: bold;
`;

Despite trying these solutions, I still cannot render a before or after element. I have verified that the content is properly referenced and a height is specified in rem. I am using Styled Components version "^5.3.5", cleared cache, deleted the public directory, and tested in both Chrome and Firefox, but the quotes are not being rendered.

Research

  • Before and After pseudo classes used with styled-components
  • Using Styled Components and passing props to psedo element before not working
  • Can anyone tell me why before not working on styled components?
  • Why is :before pseudoelement rendered before content, not element?
  • Styled-components multiple Pseudo Elements

What am I doing incorrectly, and how can I successfully render pseudo elements?

Answer №1

UPDATED RESPONSE:

@zharkov-ruslan is absolutely correct. Make sure to properly escape the backslash (\) in the content property. Here is an example of the correct usage:


const Bar = styled.p`
    font-weight: bold;

    &::before {
        content: "\\201C";
        display: block;
        font-size: 4rem;
        font-weight: 700;
        height: 4.25rem;
    }
    &::after {
        content: "\\201D";
        display: block;
        font-size: 4rem;
        font-weight: bold;
        height: 2.625rem;
    }
`;

Instead of directly inserting the character as a string, you can also use CSS keywords like open-quote and close-quote.


const Bar = styled.p`
    font-weight: bold;

    &::before {
        content: open-quote;
        display: block;
        font-size: 4rem;
        font-weight: 700;
        height: 4.25rem;
    }
    &::after {
        content: close-quote;
        display: block;
        font-size: 4rem;
        font-weight: bold;
        height: 2.625rem;
    }
`;

Answer №2

It seems like there may be an issue with the content property within the pseudo elements. I made some changes to the values in those fields and the styles worked perfectly with &:before, &:after.

const Bar = styled.p`
  &:before {
    content: "“";
    display: block;
    font-size: 4rem;
    font-weight: 700;
    height: 4.25rem;
  }

  &:after {
    content: "”";
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 2.625rem;
  }

  font-weight: bold;
`;

Answer №3

The initial method outlined in this response:

&:before {
    content: "“";
    display: block;
    font-size: 4rem;
    font-weight: 700;
    height: 4.25rem;
  }

  &:after {
    content: "”";
    display: block;
    font-size: 4rem;
    font-weight: bold;
    height: 2.625rem;
  }

was used as a temporary fix, but it wasn't the preferred approach because the reason behind the code restriction was unclear.

Another solution proposed

The quotes need to be escaped.

const Foo = styled.p`
    font-weight: bold;

    &::before {
        content: "\\201C\";
        display: block;
        font-size: 4rem;
        font-weight: 700;
        height: 4.25rem;
    }
    &::after {
        content: "\\201D\";
        display: block;
        font-size: 4rem;
        font-weight: bold;
        height: 2.625rem;
    }
`;

turned out to be incorrect. The problem stemmed from incorrectly escaping the backslash (\). It was highlighted in other discussions that using single quotes is a more recommended approach.

The effective resolution to fix the issue with the code involved properly terminating the backslash:

const Foo = styled.p`
    font-weight: bold;

    &::before {
        content: '\\201C';
        display: block;
        font-size: 4rem;
        font-weight: 700;
        height: 4.25rem;
    }
    &::after {
        content: '\\201D';
        display: block;
        font-size: 4rem;
        font-weight: bold;
        height: 2.625rem;
    }
`;

Answer №4

My typical approach when working with pseudo elements is:

  • Apply 'position: relative' to the parent element.
  • Use 'position: absolute' for the child element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating Webpack into an already established React application

After creating the initial piece of my app with create-react-app, I realized that it primarily uses npm for various tasks such as building and running locally. I'm interested in transitioning to Webpack while keeping the existing setup intact, but I ...

What are some ways to keep the text within the boundaries of the input box?

How can I prevent the letters from extending beyond the bar when typing a lot of characters? Your assistance in resolving this issue is greatly appreciated. <div id="tasks-container"> <div id="tasks-header"> ...

Next Image is encountering the ERR_TLS_CERT_ALTNAME_INVALID error when attempting to load an external URL

I have set up a custom domain with a subdomain that points to an AWS S3 bucket, such as images.domain.com. Users are able to upload images and view them in the bucket. The URL for each image is stored in the user's data in the database. However, when ...

Using Function Call to Generate Components in React

Being tired of repeatedly defining states to render Components based on conditions, I often find myself just wanting to display notifications or alerts. My current dilemma is figuring out how to render a component by invoking a function from within that co ...

Incorporating SCSS directly in React component along with material-ui styling

I'm having trouble incorporating styles into my React component. I'd prefer to use SCSS instead of either using the withStyle function or importing a plain CSS file into a JS file. For instance, I would like to import my SCSS file into ButtonCom ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

Text input field with uneditable text displayed at the end

Click here to view the input field I am looking to create an input field that always displays a "%" at the end of the input. Here is what my react component looks like currently: <StyledBaseInput type="text" ...

Disable the height property in the DOM when implementing the jQueryUI resizable feature

I'm utilizing the flex property to create a responsive layout for my web application. In order to enable resizing of my navigator panel, I have implemented jQuery UI. However, upon triggering the resize event, jQuery UI is adding a hardcoded height t ...

Unable to utilize React hooks in Next.js header

Welcome to my website . I am looking to reduce the padding on the header when the user scrolls. To achieve this, I have created the following component: import Link from 'next/link' import Image from 'next/image' import { GET_HEADER ...

Having trouble getting two components to return in React

After successfully implementing the Hello World example by returning "Hello" and "world" from two different components, I encountered a problem with my code. In this specific code snippet, I am unable to return the Menubar component, although the Map compo ...

I am trying to verify my code, but the messages are not displaying under the username. They only appear under the password field. I am not sure where I have made a mistake

Having trouble with my login form validation using jQuery. Can someone help me fix it? $(document).ready(function() { $("#form1").validate({ rules: { username: { required: true, minlength: 6 }, password: { ...

I have encountered an issue with my component and I am seeking assistance to identify the problem

Having an issue with my custom "hello world" component. 'Message' is not a valid JSX element type. Its type '() => void' cannot be used as a JSX component. Type '() => void' is not compatible with '(props: any ...

Why isn't my equality function in React.memo getting triggered?

I am facing an issue with a parent component that displays a list of children based on an array passed through props. import React from 'react'; import PropTypes from 'prop-types'; import shortid from 'shortid'; import { Cont ...

How can I properly customize and expand upon a Material UI ListItem component?

I'm currently working with TypeScript version 3.4.5 and Material UI version 4.2. I have the following code snippet: interface MyItemProps { name: string; value: string; } function Item({ name, value, ...props }: ListItemProps<'li&apo ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

What is the compatible version of Material UI with React 15.5.4?

Currently working on a project in React version 15.5.4 and looking to integrate Material UI into the app. However, I keep encountering an error stating that React version 16.3.0 or higher is required whenever I attempt to install and incorporate Material ...

Steps for integrating a video into the Bootstrap navigation bar

I've been working on a Bootstrap menu design that features text on the left side and a video on the right. My goal is to make the video extend to the top of the page with a button overlaid, similar to the image I have in mind. However, I've encou ...

Challenges encountered while implementing generic types in TypeScript and React (including context provider, union types, and intersection

I have a fully functional example available at this link: The code is working properly, but TypeScript is showing some errors. Unfortunately, I've run out of ideas on how to make the code type safe. I've searched extensively for examples that ma ...

What is the best way to align the middle item of a flexbox using CSS?

I am attempting to present text divided into 3 divs - the middle div contains the highlighted portion of the text, while the first and last divs contain the text before and after the highlighted section. Both the first and last flex items have classes tha ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...