Adjust the burger menu color based on the background color of the section

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)")};
  }
`;

Answer №1

To customize the appearance of hamburger menus on different pages with unique backgrounds, CSS can be utilized to individually style each menu per page. One approach is to assign a distinct ID to the body element for each page, and then reference that ID along with the hamburger menu in the CSS for styling purposes.

For instance:

<body id="homepage">
<nav class="hamburger">
</body>

For another page:

<body id="about-us">
<nav class="hamburger">
</body>

In the accompanying CSS:

#homepage .hamburger {
your styles
}
#about-us .hamburger {
your styles
}

Answer №2

Finding a simple solution to examine the background of an element and make adjustments may not be straightforward.

One possible approach could involve utilizing an intersection observer to analyze each section along with its background color. Subsequently, you can apply appropriate styles to the hamburger element. While this method may not provide the same level of automation as an auto-contrast tool, it offers a manageable and adaptable alternative.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS encounters a lack of 'Access-Control-Allow-Origin' header

I have encountered an issue with my AngularJS application. I am attempting to send data to a third-party URL for storage on their server. However, when I execute the code below, I receive the following error message: XMLHttpRequest cannot load . Response t ...

Mobile device causing issues with appendTo function

I am encountering an issue with my PHP file within an iframe that displays a form result in the parent document using jQuery code. Within the scenario, there is usage of both appendTo for a <p> and an input element. The jQuery code performs well on ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

Leveraging functions from separate ReactJS components

Is there a way to call a function (component A) from a completely separate component (component K) without any inherent relationship between them? Here is an example of the issue: Component A const ComponentA= () => { const start =()=>{ ...

Guide to organizing an express.js project structure:

When working with an Express.js application, what are the typical strategies for breaking up and modularizing the app.js file? Do developers usually keep everything in a single file, or is there a common convention for splitting it into smaller modules? ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...

execute a post request with dynamic data to API using nextjs httpService

I am trying to make a call to an endpoint located at using nestjs. However, I keep encountering the following error message: data 13 - XML tags should be given in the POST variable "data" const { data } = await firstValueFrom( this.httpService .post ...

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...

Error: In ReactJS, there is an issue where the property 'map' is not defined and cannot be read

I am currently developing an application using expressjs and reactjs. I have successfully retrieved data from the backend using expressjs, but I am encountering an issue with 'map is not a function'. import React, { Component } from "react"; imp ...

I'm having trouble getting my innerHTML command to update anything on the webpage, and the reason is eluding me

Below is the code snippet provided: <div id="js"><button onclick="document.getElementById('js').innerHTML=('<form> <input type=text name=tick1></input> <input type=text name=tick2></input> ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

Create a new storefront JavaScript plugin for Shopware 6 to replace the existing one

I am attempting to replace an existing JavaScript plugin in Shopware 6. However, the code within the plugin file does not seem to execute. Here is my main.js: import MyCookiePermissionPlugin from './plugin/my-cookie-permission/my-cookie-permission.pl ...

How to horizontally align a logo image in the appBar using Material-UI (ReactJS)

I recently incorporated a Material UI library into my React project (material-ui.com) and I've been trying to center my logo within the appbar component. Here is the code that I attempted: <AppBar position="sticky" > <Toolbar> ...

Step-by-step guide on replicating a website along with its CSS styles and scripts

I've been exploring the idea of cloning a webpage, such as Instagram's login page, along with its CSS elements and JavaScript, to use locally. Basically, I want to duplicate the login page and host it on my test server in a way that allows it to ...

Differences between using ng-pattern and scripting for validation

My goal is to validate a date in the format YYYY/MM/DD using a regular expression ng-pattern. When I use the code below in the UI, it works perfectly fine. <input type="text" class="k-fill" ng-pattern="/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d ...

What is the process for creating an index signature for a type alias representing a Map in Typescript?

Suppose I have a custom type for a Map as follows: type MyCustomMap = Map<string, number>; Is there any way to add an index signature to this type so that I can set key-value pairs after initializing it? I have been able to achieve this with types ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

Is there a way to resolve the Helvetica issue in NextJS when using pdfkit-Table?

Having some trouble generating a PDF file as I keep encountering the following error message: ⨯ Error: ENOENT: no such file or directory, open 'C:\Users\HECTOR\Documents.next\server\vendor-chunks/data/Helvetica.afm' err ...

C# MVC - Enabling dynamic row addition in an HTML table with multiple fields consolidated into a single cell

Hello, I'm new to c# MVC and could use some guidance. Currently, I am utilizing an example from Matt Lunn (here) to dynamically add new items to a bound list within an HTML table. However, the issue is that all the new items are being added to the fir ...