Search code examples
reactjsstyled-components

Styled Component underline hover


How would you translate this kind of psuedo effect to a styled component. E.g the exact same underline, but all stored within one const CSS in JS effect.

I'd like to build the following, but not sure how to write this into a styled comp

a::after {
    content: "";
    display: block;
    margin-top: 10px;
    margin-left: auto;
    margin-right: auto;
    height: 2px;
    width: 0px;
    background-color: tomato;
}

Solution

  • I've created a codesandbox at https://codesandbox.io/s/ecstatic-leaf-oj1my?file=/src/App.js

    Given below is the code for completeness. I've added a hover so you can easily see that the styles are being applied. Try changing the height in your pseudo element to see that your styles for the pseudo element are being applied too.

    import "./styles.css";
    import styled from "styled-components";
    const StyledAchor = styled.a`
      color: blue;
    
      &:hover {
        color: white;
      }
      &::after {
        content: "";
        display: block;
        margin-top: 10px;
        margin-left: auto;
        margin-right: auto;
        /* try changing the height to see the after pseudo element is being applied   */
        height: 20px;
        width: 0px;
        background-color: tomato;
      }
    `;
    export default function App() {
      return (
        <div className="App">
          <StyledAchor href="/">styled anchor tag</StyledAchor>
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }