How can I make the burger icon responsive and centered in my navbar?

Struggling to center the burger icon in the navbar has been a bit of a challenge for me. Although it appears centered on small mobile devices, the icon shifts to the upper side on larger screens like tablets, losing its centered position. I am seeking advice on how to make this responsive across different screen sizes.


<!DOCTYPE html>
<html>
<head>
<style>

.centerBurger {
    display: flex;
    justify-content: center;
}


.centerBurger {
    width: 100%;
    text-align: center;
}


.centerBurger {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 56.5%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
       height: 100%;
    width: 100%;
 
} 

.centerBurger  {
 display:block;  
 cursor:pointer;
 max-width:100%;
 height:auto;
}

.burgerCenter{
margin:0 auto;
 left: 50%;
 position: relative;
transform: translateX(-50%);
}


</head>
<body>
<!-- Top Navigation Menu -->
        <div class="topnav">
            
        <a href="index.html" class="active"><img src="header.png" width="25%"></a>
            
        <!-- Navigation links (hidden by default) -->
        <div id="myLinks">
            
            <a href="index.html">Home</a>
            <a href="about.html">About Us</a>
            <a href="services.html">Services</a>
            <a href="references.html">References</a>
            <a href="contact.html">Contact</a>
            <a href="privacy.html">Privacy Policy</a>
            
        </div>
            
        <!-- "Hamburger menu" / "Bar icon" to toggle the navigation links -->
        
        <a href="javascript:void(0);" class="icon centerBurger" onclick="myFunction()">
            
            
                
           <i class="fa fa-bars centerBurger"></i> 
            
        </a>
        </div>
        
                  <script>
          function myFunction() {
          var x = document.getElementById("myLinks");
          if (x.style.display === "block") {
              x.style.display = "none";
          } else {
              x.style.display = "block";
          }
          }
</script>
</body>
</html>

I have experimented with various CSS rules to center the icon, including applying them directly to the element and using a parent div to contain the icon. Unfortunately, none of these approaches have yielded the desired result.

As a newbie to coding with limited English proficiency, I would like to apologize in advance for any mistakes. Any guidance on what I may have done wrong or how to resolve this issue would be greatly appreciated.

Thank you for your help!

Answer №1

To achieve center alignment, include the property align-items: center; in your initial .centerBurger class.

Answer №2

Consider the following suggestions:

<style type="text/css">
.topnav *:not(.centerBurger) { float: left; }
.topnav .centerBurger {
display: block; 
width: fit-content; 
margin-left: auto; 
margin-right: auto; 
}
.topnav #myLinks { display: none; }

The first CSS rule allows all elements in the navigation bar except for the .centerBurger to float to the left. This prevents the .centerBurger from appearing on a separate row underneath.

The second rule centers the .centerBurger within the navigation bar. You can also specify the width of the burger image in pixels instead of using fit-content.

Alternatively, you can try this:

<style type="text/css">
.topnav { text-align: center; }
.topnav *:not(.centerBurger) { float: left; }
.topnav #myLinks { display: none; }

Answer №3

Thanks so much for your help in solving my query. After experimenting with various options, I decided to replace the <i> tag with an

<img src="burgericon.svg>
, and it worked like a charm. Here's what the updated code looks like:

´´´´
<div class="topnav">
            
        <a href="index.html" class="active"><img src="header.png" width="25%"></a>
            
        <!-- Navigation links (hidden by default) -->
        <div id="myLinks">
            
            <a href="index.html">Home</a>
            <a href="about-us.html">About Us</a>
            <a href="services.html">Services</a>
            <a href="references.html">References</a>
            <a href="contact.html">Contact</a>
            <a href="privacy.html">Privacy Policy</a>
            
        </div>
            
        <!-- "Hamburger menu" / "Bar icon" to toggle the navigation links -->
            
        <a href="javascript:void(0);" class="icon" onclick="myFunction()">
            
            
          
           <img src="bars-svgrepo-com.svg" class="svg">
            
        </a>
            
        </div>

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

Tips for incorporating flow and TypeScript typings into an NPM module

Are there any resources available for adding both flow and typescript typings to an NPM module at the same time? I've been struggling to find a comprehensive guide on this topic, and it seems to be a common issue faced by open source library maintain ...

Adding Information to a Material Design Card

Currently, I am delving into frontend development and honing my CSS skills. In my latest project, I have incorporated a mat card which can be viewed in the linked image https://i.sstatic.net/TEDcg.png. Below is an excerpt of my code: <div class=&quo ...

Superior method to ensure the child element's border overlaps with that of the parent

I am currently working on a project that requires a unique CSS effect: Let me explain exactly what I am trying to achieve: The main element (referred to as the title) has padding and a 2px bottom border. Inside this, there is a child element (known as ti ...

Setting the minimum and maximum width of the MenuItem (popover) in Material-UI based on the width of the select component

I need the popover width to always match the width of the select component, regardless of the length of the text in the menu items. Setting autoWidth to either true or false is not providing a solution. Below is the code for the select component: import ...

Struggling to generate an HTML table using JSON data

Struggling with generating an HTML table from JSON data, I'm inexperienced and having trouble with the logic. The JSON data I have needs to populate a complex dynamic HTML table. The design of the table is intricate, making it challenging for me to i ...

HTML is appearing as unformatted text on the screen

I am utilizing deta for rendering cloud-based HTML content. Below is the code snippet in use: from deta import Deta from fastapi import FastAPI, Request, Response, Form, File, UploadFile from fastapi.templating import Jinja2Templates from fastapi.response ...

node js retrieves information from the request body

Hey there! I'm diving into the world of Node.js and JavaScript, but I've hit a roadblock. I'm trying to fetch data from a URL using node-fetch, then parse it as JSON. However, I keep running into the issue of getting 'undefined' in ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...

What is causing the issue with the .change() function not functioning properly?

Recently, I encountered a situation where I had the following HTML code: <span class="offersReceivedCount">3</span> My goal was to trigger some code whenever the value of 3 changed to something else. In order to achieve this, I used Handlebar ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

Jimdo: Generate a spinning sliced circle with the click of a button

I'm attempting to achieve a spinning CD/Disk effect when the play button is clicked. I have a sample code below that represents the player's state during playback. What I envision is an image with a play button on top. Upon clicking the button, ...

Guide on retrieving a file through an HTTP request with restricted cross-origin access restrictions

Having some issues with downloading files from specific links, such as . My goal is to automate the download process for these redirected files. The challenge I'm facing is that trying to access the link directly through a web browser just gives me a ...

Click text when using the Google Tag Manager - gtm.click {{Click Text}}

I have a list of shops with detailed information like opening hours and phone numbers. When a user clicks on the shop's name, I want the relevant details to appear using javascript. I am trying to capture the shop's name (SHOP NAME) when a user ...

Tips for creating a div that covers the entire screen and prevents it from resizing

I am facing an issue with a container having the className "container". When I set the height to 100vh like this: .container{ height:100vh } Whenever I resize my screen, such as with dev-tools, the div also shrinks. How can I prevent this? Is it possi ...

Storing a string in localStorage versus $localStorage in Angular 1 yields distinct value differences

I have encountered an issue in my angular controller where I am trying to save a token returned from an API endpoint as a string. In this example, I have used the variable testData instead of the actual token. var testData = "testdata" $localStorage[&apo ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Integrating blade code within blade code

Struggling to craft a button using the Form builder. {!! Form::button('<span style="color: {!! $colour[$i] !!}" class..') !!} The specific details of the button don't matter, all I wanted was to adjust the font color to $colour[$id]. Th ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...