Currently, I am working on creating a hamburger menu component with fixed positioning using the 'fixed' property. The menu icon consists of three white lines by default, but I want them to change to black when placed in a white section. I have tried using the methods for contrasting text against backgrounds proposed on CSS-Tricks, but it didn't work as expected. The background color needs to be set in the parent div of the component for it to take effect which makes it challenging to implement dynamically based on the background color. If anyone has any suggestions or knows of an npm package that can handle this color change based on the background, please let me know.
Additionally, it's important to note that each page might have a different background color and the navigation elements need to adapt accordingly as they are called as a separate component on all pages.
Below is the code snippet for the hamburger menu implemented in Next.js with TypeScript:
import { StyledHamburger } from "./Hamburger.styled";
export type Props = {
open: boolean;
setOpen: (v: boolean) => void;
};
const Hamburger = (props: Props) => (
<StyledHamburger open={props.open} onClick={() => props.setOpen(!props.open)}>
<div></div>
<div></div>
<div></div>
</StyledHamburger>
);
export default Hamburger;
Styles:
import styled from "styled-components";
import { colors } from "../global";
export const StyledHamburger = styled.button<{ open: boolean }>`
position: fixed;
width: 2rem;
height: 2rem;
padding: 0;
background: transparent;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
border: none;
cursor: pointer;
outline: none;
z-index: 2;
div {
position: relative;
width: 2rem;
height: 0.25rem;
border-radius: 0px;
transition: all 0.3s linear;
transform-origin: 1px;
background-color: ${({ open }) =>
open ? colors.black : colors.white};
:first-child {
transform: ${({ open }) => (open ? "rotate(45deg)" : "rotate(0)")};
}
:nth-child(2) {
opacity: ${({ open }) => (open ? "0" : "1")};
transform: ${({ open }) => (open ? "translateX(20px)" : "translateX(0)")};
}
:nth-child(3) {
transform: ${({ open }) => (open ? "rotate(-45deg)" : "rotate(0)")};
}
}
p {
position: relative;
border-radius: 0px;
transition: all 0.3s linear;
transform-origin: 1px;
background-color: ${({ open }) =>
open ? colors.black : colors.white};
transform: ${({ open }) => (open ? "translateX(20px)" : "translateX(0)")};
}
`;