How to specify styles of children on parents hover with Styled-Components?

Sometimes, we want to specify styles of children on parents hover with Styled-Components.

In this article, we’ll look at how to specify styles of children on parents hover with Styled-Components.

How to specify styles of children on parents hover with Styled-Components?

To specify styles of children on parents hover with Styled-Components, we can use the &:hover pseudo-selector to specify the styles rendered on hovering on the parent element.

For instance, we write:

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

const Container = styled.div`
  width: 100px;
  height: 100px;
  &:hover #child {
    background: green;
  }
`;

const Child = styled.div`
  width: fit-content;
  height: fit-content;
`;

export default function App() {
  return (
    <Container>
      <Child id="child">hello world</Child>
    </Container>
  );
}

We create the Container component with the styled.div tag.

Then we specify the styles applied to the element with ID child inside the Container with:

&:hover #child {
  background: green;
}

Then in App, we render the Container with Child inside it.

As a result, when we hover over the container element, we see the background of the child element turn green.

Conclusion

To specify styles of children on parents hover with Styled-Components, we can use the &:hover pseudo-selector to specify the styles rendered on hovering on the parent element.