What steps would you take to create a mobile-friendly navigation bar?

I've been attempting to optimize this navigation bar for mobile devices, exploring various methods like @media queries and the hamburger menu technique through resources like YouTube. However, none of these approaches have proven effective so far. It seems that I may need to completely rewrite the HTML structure to align with the recommended practices.

Below is my original code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Waverly Farm: Home</title>
        <link href="style.css" rel="stylesheet"/>
    </head>
    <body>
        <header class = "header">
            <div class = "logo">Waverely Farm</div>
            <nav class = "navbar">
                <a href ="index.html">Home</a>
                <a href ="about_us.html">About Us</a>
                <a href ="services.html">Services</a>
                <a href ="shop.html">Shop</a>
                <a href ="contactus.html">Contact Us</a>
            </nav>
        </header>
    </body>
</html>

Although I attempted using @media queries, I'm uncertain about leveraging it effectively for this specific type of navigation bar.


* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Poppins", sans-serif;
}

.header{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 20px 100px;
    background-color: aquamarine;
    display:flex;
    justify-content: space-between;
    align-items: center;
    z-index: 100;
}
.logo{
    font-size: 32px;
    color: #fff;
    text-decoration: none;
    font-weight: 700;
}
.navbar a{
    position: relative;
    font-size: 18px;
    color: #fff;
    font-weight: 400;
    text-decoration: none;
    margin-left: 40px;
}

.navbar a::before{
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    width: 0;
    height: 2px;
    background: #fff;
    transition: .3s;
}

.navbar a:hover::before{
    width: 100%;
}

Answer №1

document.querySelector(".mobile-menu-icon").addEventListener("click", function () {
    var navbar = document.querySelector(".navbar");
    var header = document.querySelector(".header");

    if (navbar.style.display === "flex") {
        navbar.style.display = "none";
        header.classList.remove("mobile-menu-open");
    } else {
        navbar.style.display = "flex";
        header.classList.add("mobile-menu-open");
    }
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Poppins", sans-serif;
}

.header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 20px 100px;
    background-color: aquamarine;
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 100;
}

.logo {
    font-size: 32px;
    color: #fff;
    text-decoration: none;
    font-weight: 700;
}

.navbar {
    display: flex;
}

.navbar a {
    font-size: 18px;
    color: #fff;
    font-weight: 400;
    text-decoration: none;
    margin-left: 40px;
}

.mobile-menu-icon {
    display: none;
    flex-direction: column;
    cursor: pointer;
}

.bar {
    width: 25px;
    height: 3px;
    background: #fff;
    margin: 4px 0;
}

@media (max-width: 768px) {
    .navbar {
        display: none;
        flex-direction: column;
        position: absolute;
        top: 60px;
        left: 0;
        background: aquamarine;
        width: 100%;
        text-align: center;
    }

    .navbar a {
        margin: 10px 0;
    }

    .mobile-menu-icon {
        display: flex;
    }
}

.header.mobile-menu-open .navbar {
    display: flex; 
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <title>Waverly Farm: Home>
</head>
<body>
    <header class="header>
        <div class="logo>Waverely Farm>
        <nav class="navbar>
            <a href="index.html>Home>
            <a href="about_us.html>About Us>
            <a href="services.html>Services>
            <a href="shop.html>Shop>
            <a href="contactus.html>Contact Us>
        </nav>
        <div class="mobile-menu-icon>
            <div class="bar></div>
            <div class="bar></div>
            <div class="bar></div>
        </div>
    </header>
</body>
</html>

Answer №2

To create a mobile menu with a toggle button that is accessible, JavaScript is required. Fortunately, the process is quite straightforward. Here's an approach that I find effective:

HTML

Start by adding a button element for toggling the menu inside the <nav> element. It's recommended to wrap the menu links in a list element for semantic grouping.

<header class="header">
  <div class="logo">Waverely Farm</div>
  <nav class="navbar" aria-label="main">
    <button
      class="menu-toggle"
      aria-expanded="false"
      aria-controls="menu"
    >Menu</button>

    <ul id="menu" class="menu" role="list">
      <li>
        <a href="index.html">Home</a>
      </li>
      <li>
        <a href="about_us.html">About Us</a>
      </li>
      <li>
        <a href="services.html">Services</a>
      </li>
      <li>
        <a href="shop.html">Shop</a>
      </li>
      <li>
        <a href="contactus.html">Contact Us</a>
      </li>
    </ul>
  </nav>
</header>

The ARIA attributes on the button element aid screen reader users in navigating the menu effectively. Specifically, aria-expanded provides information on the menu state (open/closed).

CSS

Utilize the aria-expanded state to apply conditional styles in CSS.

:where(ul, ol)[role="list"] {
  list-style: none;
}

.menu {
  display: flex;
  flex-wrap: wrap;
}

.menu-toggle {
  display: none;
}

@media screen and (max-width: 600px) {
  .menu-toggle {
    display: initial;
  }
  button[aria-expanded="false"] + ul {
  display: none;
  }
  .menu {
    flex-direction: column;
    flex-wrap: nowrap;
    position: absolute;
    inset: 130px 0 0;
    text-align: center;
  }
  .menu a {
    color: inherit;
  }
}

The styles within .menu are just a starting point; customize them according to your preferences.

JavaScript

Lastly, add an EventListener to the menu button to toggle the aria-expanded attribute between true and false:

const menuButton = document.querySelector(".menu-toggle");

menuButton.addEventListener("click", () => {
  const state = menuButton.getAttribute("aria-expanded") === "false";
  menuButton.setAttribute("aria-expanded", state);
});

This guide should assist you in creating an accessible mobile menu with a toggle button. If you have any questions or need clarification, feel free to ask.

Answer №3

If you're looking to enhance your webpage design, you might want to consider incorporating a CSS framework such as Bootstrap:

Simply add these lines to the head of your page:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54363b3b20272026352414617a677a66">@example.com</a>/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7d70706b6c6b6b6d7e6f5f2a312c311d">@example.com</a>/dist/js/bootstrap.bundle.min.js"></script>
Then, structure your navigation bar like this:

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 3</a>
      </li>
    </ul>
  </div>
</nav>

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

When the mouse hovers over DIV2, the background image of DIV1 will be replaced

I have a full-screen background div with the ID #background-change. Within that full-screen background, I have 3 Divs named .fullscreen-column-1, .fullscreen-column-2, etc. My goal is to change the background image of #background-change when the mouseove ...

Select the hidden HTML option value automatically according to the previous option selected

I am working on a form that includes 2 select tags with the options male and female. The first select, "gender", is visible to the user while the second select, "age", is hidden. <select name="gender"> <option value="1">Male</option> ...

Using javascript to determine the vertical position of an element within a fixed container

I'm facing a challenge in determining the vertical position of an element using scrollTop when the parent container has a position: fixed. When I use scrollTop, it consistently returns a value of 0. This probably occurs because the element is no long ...

Create dynamic animations on HTML text using CSS

Looking to add some flair to your website with a text animation? How about making the text automatically glide from one side to the other like a ticker display? Any suggestions for simple CSS code to achieve this would be greatly appreciated! Thanks in ad ...

"Unusual" symbols encountered during PDF file saving

I have a PDF file titled "SA Pias - Margaça Branco.pdf" that I need to access. Currently, I am using this link: href="SA Pias - Marga%E7a Branco.pdf" Although the file opens fine in the browser, when users try to save it, they see strange characters ins ...

The second post request is encountering an issue where Request.body is not defined

After researching for similar symptoms, I couldn't find a case that matches mine. I have body-parser properly installed and app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true})) configured accordingly. However, when handl ...

Can the ID attribute be used in the closing tag of an HTML element

Could this code be improved by properly closing the div with an ID: <html> <body> <div id="main"> </div id=main"> </body> </html> ...

Align an element in the middle next to its sibling element

Utilizing the pagination component in Bootstrap, the structure of the pagination itself is quite straightforward: <ul class="pagination"> <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">&laquo; ...

Strange Vertical Offset Issue with Custom Fonts in CSS

I have implemented a custom font in my CSS using the following method: @font-face { font-family: 'Gabriola'; src: url('Gabriola.eot'); src: url('Gabriola.eot?#iefix') format('embedded-opentype'), ...

Utilizing the PHP function to return a href attribute value

I'm relatively inexperienced with php, so I'm unsure of its capabilities; My goal is to invoke a php function within an href tag and utilize the output as the tag itself.. For instance, consider the following code: HTML <a href= 'tele.p ...

Transferring HTML elements between pages

I'm currently working on a project with 4 tabbed views, each housed in separate HTML pages. Each view contains several SVG charts created using d3.js. Now, the client wants to be able to easily cut, paste, or move charts from one tabbed view to anothe ...

Include image hover text without using HTML

I am looking to add a hover effect to some images using CSS and JS since I cannot directly edit the HTML file. The goal is to have centered text pop out when hovering over certain images. I know the div class of the image but unfortunately, I cannot add te ...

Using jQuery to Verify the Input Type of a Select Option

I am looking to learn how I can validate the input of a select option value. Currently, I have a function that allows me to validate radio buttons: <div id="gender"> <input type="radio" name="Gender" value="Male">Male <br /> &l ...

Tips for adding a label element within the Semantic UI + React Dropdown component

I am trying to replicate the Dropdown component from Semantic UI using UI React, where a <label> is included for the dropdown menu: https://i.sstatic.net/XcAGw.png () Here is the markdown code I want to generate in my React app: <div class="ui ...

Guide to efficiently centering the background image in your existing Bootstrap template

I'm currently working on ensuring that the background image stays within the user's window, regardless of the device being used. While I have successfully added the background image, I am facing challenges in centering it properly. The current ou ...

Contrast the text within two div elements using jQuery and modify the color of any identical words

i have a pair of div's with sentences inside first div: i keep an expensive pen in my pocket. second div i own an expensive watch. given the above two divs, I aim to compare the sentences and identify the common words present in both. ...

How was the HTML code on this website masked so effectively?

While browsing the internet, I stumbled upon a website and decided to take a peek at its source code. DCARD You can find screenshots here Unfortunately, the content is in Chinese. It seems like this website is similar to a forum in my country. What cau ...

Restore background color when clicked outside

I'm currently using this code to both load content from a div and change the color of the tab when a user clicks on it. However, I'm struggling to find a way to revert the background color back once the user clicks on something else. Any suggesti ...

html - displaying a new page within the content of the current page

I have a question about basic HTML knowledge that I find embarrassing Is it possible to open or load a second page within my first page? I want a menu button that will load the second page. <li class="current"><a href="first.html" target = "myC ...

When using the app.get() method in Express.js to send HTML files, external CSS and JS files may not be recognized, causing the HTML file to be deployed

I recently encountered an issue while trying to load CSS and JS files in my Express.js project. Despite following various methods, including setting up a static public folder and handling requests individually, I couldn't get the stylesheets and scrip ...