Creating a navigational bar in HTML that is both centered and responsive is a great way to enhance the

I've been working on creating a navigation bar for my website that is not only centered but also responsive. I've encountered an issue where, upon resizing the browser window to a very small width, the links disappear and are replaced by an icon in the top right corner. Clicking on this icon reveals the links in a different layout. I've tried various methods to center my navigation bar, but they have mostly resulted in it becoming misaligned. While I am familiar with how to center a non-responsive nav bar, I really like the responsiveness of this design as it would look great on mobile devices. If anyone has any tips to help me achieve perfect alignment while maintaining responsiveness, I would greatly appreciate it!

 .topnav {
                overflow: hidden;
                background-color: #333;
            }
              
              .topnav a {
                float: left;
                display: block;
                color: #f2f2f2;
                text-align: center;
                padding: 14px 16px;
                text-decoration: none;
                font-size: 17px;
              }
              
              .topnav a:hover {
                background-color: #ddd;
                color: black;
              }
              
              .topnav a.active {
                background-color: #4CAF50;
                color: white;
              }
              
              .topnav .icon {
                display: none;
              }
              
               @media screen and (max-width: 600px) {
                .topnav a:not(:first-child) {display: none;}
                .topnav a.icon {
                  float: right;
                  display: block;
                }
              }
              
              @media screen and (max-width: 600px) {
                .topnav.responsive {position: relative;}
                .topnav.responsive .icon {
                  position: absolute;
                  right: 0;
                  top: 0;
                }
                .topnav.responsive a {
                  float: none;
                  display: block;
                  text-align: left;
                }
              }
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>

    <body>
        <div class="topnav" id="myTopnav">
            <a href="#news" class="active">HOME</a>
            <a href="#news">SERVICES</a>
            <a href="#contact">PRODUCTS</a>
            <a href="#news">CONTACT</a>
            <a href="#news">CALCULATORS</a>
            <a href="javascript:void(0);" class="icon" onclick="myFunction()">
              <i class="fa fa-bars"></i>
            </a>
        </div>

      <script>
      function myFunction() {
              var x = document.getElementById("myTopnav");
              if (x.className === "topnav") {
                x.className += " responsive";
              } else {
                x.className = "topnav";
              }
            }
      </script>
    </body>
</html>

Answer №1

Is this the style you're looking for?

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {
    position: relative;
  }
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}

@media screen and (min-width: 600px) {
  .topnav {
    display: flex;
    justify-content: center;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>
  <div class="topnav" id="myTopnav">
    <a href="#news" class="active">HOME</a>
    <a href="#news">SERVICES</a>
    <a href="#contact">PRODUCTS</a>
    <a href="#news">CONTACT</a>
    <a href="#news">CALCULATORS</a>
    <a href="javascript:void(0);" class="icon" onclick="myFunction()">
      <i class="fa fa-bars"></i>
    </a>
  </div>

  <script>
    function myFunction() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
        x.className += " responsive";
      } else {
        x.className = "topnav";
      }
    }
  </script>
</body>

</html>

@media screen and (min-width: 600px) {
  .topnav {
    display: flex;
    justify-content: center;
  }
}

Answer №2

If you want to center the tag elements within the collapsed bar, simply change the "text-align" property from "left" to "center" to effectively center the navbar items.

  • Avoid duplicating the same media query code if you are not modifying the screen width; consolidate the code into a single query for efficiency.
@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {
    display: none;
  }

  .topnav a.icon {
    float: right;
    display: block;
  }

  .topnav.responsive {
    position: relative;
  }

  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }

  .topnav.responsive a {
    float: none;
    display: block;
    text-align: center;
  }
}

Answer №3

Did you attempt inserting this code snippet into the head section of your website?

<meta name="viewport" content="width=device-width, initial-scale=1">

I apologize for not being able to access my desktop sooner to make edits to my previous message.

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

Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window? You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/ I would like the image to be already scaled vertic ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

Tips for adjusting the dimensions of a map within the app.component.html

Within the code snippet below, my aim is to adjust the width and height of the map using the style tag shown here: <style> #map3 .map { width: 100%; height:90px; } </style> Despite trying various values for width an ...

Eliminating every single dynamic 'data attribute' from a specific Element

Within my div element, dynamic data- attributes are added to some tags. (The names of these data- attributes are generated dynamically by a script, so the exact name is unknown) <div data-1223="some data" data-209329="some data" data-dog="some value"&g ...

What is the reason for the reconnect function not activating when manually reconnecting in Socket.IO?

After disconnecting the client from the node server using socket.disconnect(true);, I manually re-establish the connection on the client side with socket.open(). The issue arises when triggering socket.open(); the socket.on('reconnect', (attempt ...

Exploring the functions of `map` and `filter` in the world of

Consider this input: var m = [{ name: 'foo', routes: [{verb: 'post', path: '/foo1'}, {verb: 'get', path: '/foo2'}] }, { name: 'bar', routes: [{verb: 'put', path: ...

When the React ref current is accessed from outside the component where it is initialized, it returns

Encountering an issue with React ref. Today, I was pondering on how to access DOM elements from sub-components within a main component. Fortunately, I stumbled upon a solution using React refs on a website. I set up a ref in my main component and linked i ...

Purging Browser Cache after releasing a new update

My web application is built using ASP.Net MVC + angular and currently has over 500 active users. We encounter a recurring issue whenever we perform a new publish or release - we have to instruct our users to clear their browser cache, which can be quite f ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

Switch up the hover color of the dropdown menu in the Bootstrap navbar

I'm struggling to change the hover color of the dropdown menu in the navigation bar. Can anyone please help me with this? Here is my HTML code. How can I change the hover color using CSS? <div class="navbar navbar-inverse" id="menu"> <di ...

Unable to use npm module "csv-db" as it is currently experiencing functionality issues

Looking to implement a "lightweight offline database" that stores data in .csv files. The module I am using can be found in the documentation: https://www.npmjs.com/package/csv-db Unfortunately, I've been encountering issues with this module and have ...

Having difficulty retrieving data in mongodb using category id

Currently, I am attempting to sort and filter my pets based on categories. The pets are modeled as follows: const Pet = mongoose.model( 'Pet', new Schema({ name: { type: String, required: true, } ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

Calculating the size of grid thumbnails or items using the calc() function

I am currently working on building a responsive portfolio grid that spans the full width of the screen. To achieve this, I have set the width of the items using calc() and ensured that the thumbnail image fills the entire div by applying the following CSS: ...

What is the best way to send a JSON string as a prop?

I am integrating Vue.js with Shopify, and I am trying to pass objects from Liquid into a Vue component as a prop. An example scenario would involve using the product object in Liquid from Shopify and converting it directly into an object within Vue. Ideall ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...

Choose an identifier from a CSS class

I've been experimenting with a code pen that I stumbled upon: http://codepen.io/surjithctly/pen/pLDwe When I encase the checkbox in a div with the class "mynav," it stops functioning as intended. How do I implement the specified styling for the check ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Is it possible to create varied background shades in CSS3 without relying on images?

Check out this fiddle: http://jsfiddle.net/dzAJp All the divs are styled with a light blue background color using the background-color CSS property instead of background-image. I want to darken the second div slightly by combining its current background ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...