Martin Crawley
Martin Crawley

Reputation: 487

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>
);

Upvotes: 0

Views: 607

Answers (4)

Martin Crawley
Martin Crawley

Reputation: 487

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>

Upvotes: 0

Rajnish kumar
Rajnish kumar

Reputation: 196

use :hover without ''(quotes). That is CSS part, you need to write Pure CSS.

Upvotes: 1

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

The hover should be like &:hover { ... } not a text as you mentioned ,

Also be sure (inspect mode ) that this value isn't overridden at other globale css style

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

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202721

:hover is the correct accessor/selector.

const Thing = styled.p`
  color: black;
  background: none;
  width: 200px;
  padding: 20px;
  text-align: center;
  border: 1px solid white;
  margin: auto;

  :hover {
    background: red;
    text-decoration: underline; // also use correct css naming!
  }
`;

Edit pedantic-lumiere-zzoof

Upvotes: 0

Related Questions