how to change a styled component's before content on hover [emotion.js , styled components ]

3.2k views Asked by At

on button hover I want to make changes to the :before content too , I couldn't find an answer in the official documentation I wonder f this is possible . here is the css selector I want to convert to a styled component syntax is:

.button:hover::before{}

and here is the styled component :

import styled from '@emotion/styled'

export const Button =styled.button(props=>{
   return`
    padding: .75rem 2rem ;
    color: #fff;
    background-color: transparent;
    border: 1px solid #000;
    position: relative;
    z-index: 1;
    transition: all .5s cubic-bezier(0.785, 0.135, 0.15, 0.86);
    cursor: pointer;
    width: ${props.width ? props.width:'fit-content'};
    margin-top:  ${props.marginTop ? props.marginTop :0}rem;

    &:before{
         content: '';
         position: absolute;
         z-index: -1;
         height: 100%;
         width: 100%;
         top: 0;
         left: 0;
         ${props.collection?"background-color: #fff;":"background-color: var(--colorGrey);"}
         transition: all .5s cubic-bezier(0.785, 0.135, 0.15, 0.86);
         transform-origin: left center;

         //I want to change style on hover 
    }
    
    &:hover{
      color:var(--colorGrey);
    }
`})
1

There are 1 answers

3
Benjamin On BEST ANSWER

Simply nest a :before pseudo-element inside the :hover pseudo class.

Also, consider using a template literal, instead of a function that takes props.

import styled from '@emotion/styled';

export const Button = styled.button`
  padding: 0.75rem 2rem;
  color: #fff;
  background-color: transparent;
  border: 1px solid #000;
  position: relative;
  z-index: 1;
  transition: all 0.5s cubic-bezier(0.785, 0.135, 0.15, 0.86);
  cursor: pointer;
  width: ${(props) => (props.width ? props.width : 'fit-content')};
  margin-top: ${(props) => (props.marginTop ? props.marginTop : 0)}rem;

  &:before {
    content: '';
    position: absolute;
    z-index: -1;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    ${(props) => (props.collection ? 'background-color: #fff;' : 'background-color: var(--colorGrey);')}
    transition: all .5s cubic-bezier(0.785, 0.135, 0.15, 0.86);
    transform-origin: left center;
  }

  &:hover {
    color: var(--colorGrey);

    &:before {
      content: 'Hovered';
    }
  }
`;