Guide to positioning a top navigation menu with dropdown items in the center using CSS: absolute positioning

I have implemented a pure CSS menu from this source on my website. It functions properly in the 'hamburger menu' mode, but I am encountering difficulties when attempting to center or right-align the menu in other modes.

Despite trying various solutions provided in this stackoverflow thread, the menu becomes disrupted. Specifically, the list elements are placed beneath each other and/or the dropdown menus appear in incorrect locations.

Does anyone know how I can successfully center or right align this menu without causing any disruptions? Any assistance is greatly appreciated!

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>CSS Only Navigation Menu</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <label for="show-menu" class="show-menu">Show Menu</label>
    <input type="checkbox" id="show-menu" role="button">
        <ul id="menu">
            <li><a href="#">Home</a></li>
            <li>
                <a href="#">About ↓</a>
                <ul class="hidden">
                    <li><a href="#">Who We Are</a></li>
                    <li><a href="#">What We Do</a></li>
                </ul>
            </li>
            <li>
                <a href="#">Portfolio ↓</a>
                <ul class="hidden">
                    <li><a href="#">Photography</a></li>
                    <li><a href="#">Web & User Interface Design</a></li>
                    <li><a href="#">Illustration</a></li>
                </ul>
            </li>
            <li><a href="#">News</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
</body>
</html>

Answer №1

Utilize flexbox for content alignment:

@media (min-width: 768px) {    
    #menu {
        width: 100%;
        display: flex;
        justify-content: center; /* alternatively, use end */
    }
}

Answer №2

Feel free to utilize the following code snippet

body {
            margin: 0;
        }
        /*Strip the ul of padding and list styling*/        
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            position: absolute;
        }
        /*Create a horizontal list with spacing*/        
        li {
            display: inline-block;
            float: left;
            margin-right: 1px;
        }
        /*Style for menu links*/        
        li a {
            display: block;
            min-width: 140px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            color: #fff;
            background: #2f3036;
            text-decoration: none;
        }
        /*Hover state for top level links*/        
        li:hover a {
            background: #19c589;
        }
        /*Style for dropdown links*/        
        li:hover ul a {
            background: #f3f3f3;
            color: #2f3036;
            height: 40px;
            line-height: 40px;
        }
        /*Hover state for dropdown links*/        
        li:hover ul a:hover {
            background: #19c589;
            color: #fff;
        }
        /*Hide dropdown links until they are needed*/        
        li ul {
            display: none;
        }
        /*Make dropdown links vertical*/        
        li ul li {
            display: block;
            float: none;
        }
        /*Prevent text wrapping*/        
        li ul li a {
            width: auto;
            min-width: 100px;
            padding: 0 20px;
        }
        /*Display the dropdown on hover*/        
        ul li a:hover + .hidden,
        .hidden:hover {
            display: block;
        }        
        ul.hidden {
            width: 20%;
        }        
        ul.hidden li a {
            display: block;
            height: auto;
            text-align: center;
            line-height: normal;
            padding: 15px 10px;
        }
        /*Style 'show menu' label button and hide it by default*/        
        .show-menu {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            text-decoration: none;
            color: #fff;
            background: #19c589;
            text-align: center;
            padding: 10px 0;
            display: none;
        }
        /*Hide checkbox*/        
        input[type=checkbox] {
            display: none;
        }
        /*Show menu when invisible checkbox is checked*/        
        input[type=checkbox]:checked ~ #menu {
            display: block;
        }
        /*Responsive Styles*/        
        @media screen and (max-width: 760px) {
            /*Make dropdown links appear inline*/
            ul {
                position: static;
                display: none;
            }
            /*Create vertical spacing*/
            li {
                margin-bottom: 1px;
            }
            /*Make all menu links full width*/
            ul li,
            li a {
                width: 100%;
            }
            /*Display 'show menu' link*/
            .show-menu {
                display: block;
            }
            ul.hidden {
                width: 100%;
            }
        }
<label for="show-menu" class="show-menu">Menu</label>
    <input type="checkbox" id="show-menu" role="button">
    <ul id="menu">
        <li><a href="#">Home</a></li>
        <li>
            <a href="#">About ↓</a>
            <ul class="hidden">
                <li><a href="#">Who We Are</a></li>
                <li><a href="#">What We Do</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Portfolio ↓</a>
            <ul class="hidden">
                <li><a href="#">Photography</a></li>
                <li><a href="#">Web & User Interface Design</a></li>
                <li><a href="#">Illustration</a></li>
            </ul>
        </li>
        <li><a href="#">News</a></li>
        <li><a href="#">Contact</a></li>
    </ul>

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 embedding a file within a text box in HTML and enabling users to make direct edits

I am currently working on a feature that allows users to open a .txt or .html file from their file explorer and paste the contents into a textarea for editing and saving purposes. My question is whether it's possible to read the file content and auto ...

Is there a way to adjust the height of a DIV based on the background image and keep the text centered at the same time?

Currently in the process of designing a landing page for my website, and I am interested in incorporating a Jumbotron to provide a more modern and tech-savvy touch. Successfully managed to center my text both horizontally and vertically, now looking into s ...

Gulp does not generate any files

Hey there, I'm brand new to using node.js and coding in general. I recently attempted to convert SCSS to CSS using gulp. My gulpfile.js seems to be correct, but when I try running "gulp styles" in the node.js command prompt, I receive the following ou ...

The minimum height of the IE element could not fully expand within its flex container that was set to absolute positioning

Creating a webpage with a full-page layout using a content session that spans the entire height of its container is my current project. To achieve this, I have implemented the following: The content's container (div.inner) is set to be absolute-posi ...

Having trouble with implementing a static URL in CSS

I'm struggling to incorporate a static file into my CSS as a background image for my website. The static URL is functioning properly when tested in HTML, but it's not working when implemented in CSS. HTML: {% extends 'base.html' %} { ...

What is the process for making the default text in a text box appear grayed out?

Hey there! I have this cool idea for a text box. Basically, it starts off with default text but when you hover your mouse over it, the text disappears and you can start typing as usual: If you want to see how it looks like, you can check out this link: N ...

Exploring the possibilities of NodeJs by analyzing an HTML form

I'm facing an issue while evaluating an HTML Form using NodeJs and Express. Here's my JavaScript Code My aim is to manage HTML Forms in NodeJs using Express. const express = require('express'); const http = require('http'); ...

Tips on automating clicking the cookie button using Selenium?

Currently, I am attempting to extract data from the following website. I need to access various subpages, but some of them are hidden behind a "load more" button. I decided to use Selenium to click the button, but I am encountering difficulty with getting ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

What might be the reason for the border not reaching the bottom of the popup in my chrome extension?

I am currently working on a Chrome extension and using Bootstrap 5 with Sass to style its popup. However, I have encountered an issue where the border of the popup does not extend to the bottom as expected. What could be causing this problem? popup.html & ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

What is the reason behind the Chrome icon flickering momentarily while loading certain web pages?

I recently put together a basic html document, here it is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <title>Just a test.</title> </head> <body> <svg ...

`Ensuring uniform height for card titles`

So here's the scenario I'm dealing with: There seems to be an issue with alignment in the dark blue boxes when they are displayed in a flex container. The top box is not aligned properly with the one next to it. How can this problem be resolved? ...

Loop through the elements retrieved by the `getElementsByName` method in

My goal is to access each node by elementName using the following JavaScript code: function myFunction() { var h1 = document.getElementsByName("demoNode"); for (var i = 0; i < h1.length; i++) { if (h1[i].name == "demoNode") { var att ...

In Javascript, the color can be changed by clicking on an object, and the color

Looking for help with my current HTML code: <li><a href="index.php" id="1" onclick="document.getElementById('1').style.background = '#8B4513';">Weblog</a></li> The color changes while clicking, but when the lin ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

The lower division remains static when the browser window is resized

Why does the div with class .lower not move to the bottom of the page when the screen is resized? Could this be because of its CSS property position:absolute;? Check out the code snippet here. #lower { width: 100%; position: absolute; bot ...

Swap the Text for a Button

I've been searching for a solution to this problem, but all I seem to find online is advice on how to "replace button text." What I'm trying to achieve is to have text change into a button when hovered over. I've attempted using fadeIn/fade ...

Manipulate images in real-time and insert custom text using JavaScript/jQuery

Within my possession is an image depicted above. My objective revolves around dynamically altering the values present at the occurrences of L, A, and B; to achieve this, I must eliminate or conceal L, A, and B while substituting them with numerical equiv ...

Switch the background color of the body when hovering over a link

Is it possible to change the page background when hovering over a a using only CSS? I am searching for a solution that does not involve any JavaScript. I understand that we can access child elements with CSS, but I am unsure if it is possible to target th ...