Search code examples
cssreactjsstyled-components

React Hover Styling


Forgive me if this has been asked before, I've gone through loads of answers and failing to get this working. Basically I'm just after adding a background color when hovering over my <p> element. I don't want to use JavaScript hover events, I want to use just CSS stylings.

Can someone explain why this doesn't work and what the common solution is? I've tried so many combinations, eg :hover {. &:hover {, ':hover': {, '&:hover': { etc.

Thanks.

import React from "react";
import styled from "styled-components";

const Thing = styled.p`
  background: none;
  width:200px;
  padding:20px;
  text-align: center;
  border: 1px solid white;
  margin: auto;
  ':hover': {
    background: red;
    textDecoration: underline;
  }
`;

export const BorderButton = ({text}) => (
  <Thing>
    {text}
  </Thing>
);


Solution

  • It turns out I had another styling on the page where this component was being rendered. Removing that style seems to have fixed it, though I don't understand why.

    <Styles>
        <div className="main">
          <h2>Home Page</h2>
          <BorderButton />
        </div>
      </Styles> 
    

    to

        <div className="main">
          <h2>Home Page</h2>
          <BorderButton />
        </div>