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

store user settings in local storage

After writing some code with a link that toggles text visibility upon click, I now want to incorporate saving this state in web storage so that it persists upon page reload. As a beginner in JavaScript and HTML, this task has proven challenging for me. Th ...

Limit the text input area in HTML to a fixed size, preventing any text from exceeding the specified boundary

Is there a way to create a fixed line text area that limits the user from typing beyond a certain number of lines and maximum width? My current CSS styling for this is as follows: .area-style { resize: none; width: 324px; height: 200px; m ...

Hovering over text can change the width of the background color

I'm currently facing a roadblock while working on my website. I have successfully adjusted the height of the list items on my navigation bar, but now I am struggling to expand the width so that when hovering over it, the background color covers a slig ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

"Troubleshooting a matter of spacing in HTML5 body

I've been struggling to eliminate the gap between the top of my webpage and the <div> element. Here's the code snippet causing the issue: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="v ...

Getting data in a ng-Dialog Modal with AngularJS is a breeze!

Hi there, I'm new to Angular JS and facing an issue with displaying data from my MySQL database in a table as well as in a modal for more detailed information: I've included the HTML file named _detail_modal.html at the bottom of the page. ...

Localhost causing variations in CSS behavior

I've been working on a website and wanted to share it with someone, so I set up a webserver. However, I've encountered some peculiar behavior when trying to access the site via LAN rather than through my localhost. Firstly, when viewing the site ...

Looking for an effective method to implement CSS styling within a list cell in JavaFX?

As a beginner in JavaFX with limited knowledge of CSS, I struggled to conduct proper research and provide relevant information here. I apologize for any confusion or duplication. I am seeking a solution to apply CSS to JavaFX controls, specifically in a Li ...

What could be causing some videos not to load on a Chrome page?

Make sure to click on the link using a webkit browser. Upon loading, you should see a 4x4 grid of videos, but in Chrome, only 1-3 videos tend to load. Interestingly, it works perfectly fine on Safari. Why is this discrepancy happening even though they a ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

Linking a DropdownList to a nested JSON outcome

I've successfully connected to an API endpoint, deserialized nested JSON results, and bound them to a gridview using Newtonsoft.Json serialization attributes. However, I'm facing issues when trying to bind the data to a dropdownlist. What is the ...

Can someone please explain how to apply various fonts to the text in a `<p>` paragraph using CSS and HTML?

Take a look at this image Can you provide guidance on how to incorporate various fonts within a paragraph, like the example shown in the image above? I am experimenting with the "Creative Corner" section. ...

Placing an item inside the container without exceeding its vertical limit

Check out this jsfiddle - http://jsfiddle.net/az47U/3/ - where you'll find a Gallery div along with a Canvas div, both located within the body. These divs have been absolutely positioned to not affect the overall body height. I've set the body he ...

Sending data to API using AngularJS Http Post

Upon clicking "Add new User", a modal pop-up will appear with a form containing a text field and a checkbox. However, upon clicking the create button, the data is not being posted to the API and the modal pop-up remains open without closing. I would like ...

jQuery Mobile and PhoneGap Contact Form

I've been trying to find a solution on my own, but so far I haven't had any luck. I'm looking for a contact form that I can integrate into my jQuery Mobile and PhoneGap application. My server runs on node.js. Does anyone have a working exam ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

Concealing the pagination buttons for next and previous in Material-UI TablePagination

Is there a way to remove the next and prev buttons in the TablePagination component without affecting the position of the "Showing ..." text? Should I handle this through CSS styling or by configuring the component settings? ...

Ways to center a spinner on the screen using CSS during loading

Upon loading the page, my spinner appears in the center of the screen after a second. However, in the initial frame of the page, it is not centered but positioned on the top-left corner instead. How can I ensure that my spinner starts off centered from the ...

Is the text alignment off?

I've been immersed in creating a website, but I encountered an issue for which I can't seem to find the solution. Check out my text alignment here (test) - it's not aligned all the way to the left of the content Here is the HTML code: < ...

Setting a specific time for a div element with opacity: A step-by-step guide

Is there a way to adjust the timing for the appearance of the add-to-cart when hovering over the product-list-item? Currently, it appears when I hover over the item and disappears when I move my mouse away. .product-list-item { position: relative; w ...