Unable to align a block element using CSS

My friend recently shared a code snippet for a menu that I wanted to use on my website. However, the CSS aligns the menu items to the left and I want them to be centered with a width of 100%. I've tried various solutions like removing float:left, changing text-align to center, and adding margin: 0px auto, but none of these worked. Here's the code for the menu:

(function($) {
    
      $.fn.menumaker = function(options) {
    
        var cssmenu = $(this),
          settings = $.extend({
            title: "Menu",
            format: "dropdown",
            sticky: false
          }, options);
    
        return this.each(function() {
          cssmenu.prepend('<div id="menu-button">' + settings.title + '</div>');
          $(this).find("#menu-button").on('click', function() {
            $(this).toggleClass('menu-opened');
            var mainmenu = $(this).next('ul');
            if (mainmenu.hasClass('open')) {
              mainmenu.hide().removeClass('open');
            } else {
              mainmenu.show().addClass('open');
              if (settings.format === "dropdown") {
                mainmenu.find('ul').show();
              }
            }
          });
    
          cssmenu.find('li ul').parent().addClass('has-sub');
    
          multiTg = function() {
            cssmenu.find(".has-sub").prepend('<span class="submenu-button"></span>');
            cssmenu.find('.submenu-button').on('click', function() {
              $(this).toggleClass('submenu-opened');
              if ($(this).siblings('ul').hasClass('open')) {
                $(this).siblings('ul').removeClass('open').hide();
              } else {
                $(this).siblings('ul').addClass('open').show();
              }
            });
          };
    
          if (settings.format === 'multitoggle') multiTg();
          else cssmenu.addClass('dropdown');
    
          if (settings.sticky === true) cssmenu.css('position', 'fixed');
    
          resizeFix = function() {
            if ($(window).width() > 768) {
              cssmenu.find('ul').show();
            }
    
            if ($(window).width() <= 768) {
              cssmenu.find('ul').hide().removeClass('open');
            }
          };
          resizeFix();
          
         return $(window).on('resize', resizeFix);

        });
       
      };
    })(jQuery);
    
    (function($) {
      $(document).ready(function() {
    
        $("#cssmenu").menumaker({
          title: "Menu",
          format: "multitoggle"
        });

        $("#cssmenu").prepend("<div id='menu-line'></div>");

        var foundActive = false,
          activeElement, linePosition = 0,
          menuLine = $("#cssmenu #menu-line"),
          lineWidth, defaultPosition, defaultWidth;
    
        $("#cssmenu > ul > li").each(function() {
          if ($(this).hasClass('active')) {
            activeElement = $(this);
            foundActive = true;
          }
        });
    
        if (foundActive === false) {
          activeElement = $("#cssmenu > ul > li").first();
        }
    
        defaultWidth = lineWidth = activeElement.width();
    
        defaultPosition = linePosition = activeElement.position().left;
    
        menuLine.css("width", lineWidth);
        menuLine.css("left", linePosition);
    
        $("#cssmenu > ul > li").hover(function() {
            activeElement = $(this);
            lineWidth = activeElement.width();
            linePosition = activeElement.position().left;
            menuLine.css("width", lineWidth);
            menuLine.css("left", linePosition);
          },
          function() {
            menuLine.css("left", defaultPosition);
            menuLine.css("width", defaultWidth);
          });
      });
    })(jQuery);

Answer №1

I believe all the necessary components are in place...this method appears to be quite effective.

   #cssmenu.align-center > ul {
      font-size: 0;
      text-align: center;
    }
    #cssmenu.align-center > ul > li {
      display: inline-block;
      float: none;
    }

body {
  background: black;
}
@import url(http://fonts.googleapis.com/css?family=Open+Sans);
 #cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a,
#cssmenu #menu-button {
  margin: 0;
  padding: 0;
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
#cssmenu #menu-button {
  display: none;
}
#cssmenu {
  width: auto;
  font-family: 'Open Sans', sans-serif;
  line-height: 1;
  background: #ffffff;
}
#menu-line {
  position: absolute;
  top: 0;
  left: 0;
  height: 3px;
  background: #009ae1;
  -webkit-transition: all 0.25s ease-out;
  -moz-transition: all 0.25s ease-out;
  -ms-transition: all 0.25s ease-out;
  -o-transition: all 0.25s ease-out;
  transition: all 0.25s ease-out;
}
#cssmenu > ul > li {
  display: inline-block;
}
#cssmenu.align-center > ul {
  font-size: 0;
  text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-center ul ul {
  text-align: left;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right ul ul {
  text-align: right;
}
#cssmenu > ul > li > a {
  padding: 20px;
  font-size: 12px;
  text-decoration: none;
  text-transform: uppercase;
  color: #000000;
  -webkit-transition: color .2s ease;
  -moz-transition: color .2s ease;
  -ms-transition: color .2s ease;
  -o-transition: color .2s ease;
  transition: color .2s ease;
}
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li.active > a {
  color: #009ae1;
}
#cssmenu > ul > li.has-sub > a {
  padding-right: 25px;
}
#cssmenu > ul > li.has-sub > a::after {
  position: absolute;
  top: 21px;
  right: 10px;
  width: 4px;
  height: 4px;
  border-bottom: 1px solid #000000;
  border-right: 1px solid #000000;
  content: "";
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  transform: rotate(45deg);
  -webkit-transition: border-color 0.2s ease;
  -moz-transition: border-color 0.2s ease;
  -ms-transition: border-color 0.2s ease;
  -o-transition: border-color 0.2s ease;
  transition: border-color 0.2s ease;
}
#cssmenu > ul > li.has-sub:hover > a::after {
  border-color: #009ae1;
}
#cssmenu ul ul {
  position: absolute;
  left: -9999px;
}
#cssmenu li:hover > ul {
  left: auto;
}
#cssmenu.align-right li:hover > ul {
  right: 0;
}
#cssmenu ul ul ul {
  margin-left: 100%;
  top: 0;
}
#cssmenu.align-right ul ul ul {
  margin-left: 0;
  margin-right: 100%;
}
#cssmenu ul ul li {
  height: 0;
  -webkit-transition: height .2s ease;
  -moz-transition: height .2s ease;
  -ms-transition: height .2s ease;
  -o-transition: height .2s ease;
  transition: height .2s ease;
}
#cssmenu ul li:hover > ul > li {
  height: 32px;
}
#cssmenu ul ul li a {
  padding: 10px 20px;
  width: 160px;
  font-size: 12px;
  background: #333333;
  text-decoration: none;
  color: #dddddd;
  -webkit-transition: color .2s ease;
  -moz-transition: color .2s ease;
  -ms-transition: color .2s ease;
  -o-transition: color .2s ease;
  transition: color .2s ease;
}
#cssmenu ul ul li:hover > a,
#cssmenu ul ul li a:hover {
  color: #ffffff;
}
#cssmenu ul ul li.has-sub > a::after {
  position: absolute;
  top: 13px;
  right: 10px;
  width: 4px;
  height: 4px;
  border-bottom: 1px solid #dddddd;
  border-right: 1px solid #dddddd;
  content: "";
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-transition: border-color 0.2s ease;
  -moz-transition: border-color 0.2s ease;
  -ms-transition: border-color 0.2s ease;
  -o-transition: border-color 0.2s ease;
  transition: border-color 0.2s ease;
}
#cssmenu.align-right ul ul li.has-sub > a::after {
  right: auto;
  left: 10px;
  border-bottom: 0;
  border-right: 0;
  border-top: 1px solid #dddddd;
  border-left: 1px solid #dddddd;
}
#cssmenu ul ul li.has-sub:hover > a::after {
  border-color: #ffffff;
}
<div id='cssmenu' class="align-center">
  <ul>
    <li><a href='#'>Home</a>
    </li>
    <li class='active has-sub'><a href='#'>Products</a>
      <ul>
        <li class='has-sub'><a href='#'>Product 1</a>
          <ul>
            <li><a href='#'>Sub Product</a>
            </li>
            <li><a href='#'>Sub Product</a>
            </li>
          </ul>
        </li>
        <li class='has-sub'><a href='#'>Product 2</a>
          <ul>
            <li><a href='#'>Sub Product</a>
            </li>
            <li><a href='#'>Sub Product</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href='#'>About</a>
    </li>
    <li><a href='#'>Contact</a>
    </li>
  </ul>
</div>

Answer №2

Have you attempted replacing "auto" with "100%"? This change can be found in the #cssmenu under "width:auto". After adjusting it to "100%", the preview shows that it is now centered.

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

Resolving DataTables Error

Here is my JavaScript code snippet. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.1/css/but ...

Guide to creating a dynamic dropdown with Ajax in Codeigniter

It feels like the [insertLongNumber]th time someone has asked this question, and despite my research efforts, I'm unable to find a fitting solution. So here it goes. I'm currently tackling a dynamic dropdown conundrum using PHP and AJAX in CodeI ...

Ways to showcase the row count in SQL query using COUNT

Upon executing the query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin, it accurately retrieves the total number of rows within my database. To further enhance this functionality, I now seek to showcase this figure on my success.php page utilizing the cou ...

Tips for inserting the final array into the designated div

While working on creating a navigation menu with dropdown and multi-menu functions, I encountered some issues that needed to be addressed. After making several improvements, there is still one area that confuses me. Perhaps I can find the solution here. ...

Tips for identifying HTML tags that include a specific attribute automatically

Is there a way to automatically identify an HTML tag that contains a specific attribute like data-wow-delay? This query revolves around wow.js. The goal is to have the classes wow bounce added automatically to any HTML tag that has this particular attribu ...

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

What is the best way to implement a CSS transition in React when the state changes, the component remounts, or it re-rend

Imagine having a React functional component with some basic state: import React, { useState } from 'react' import { makeStyles } from "@material-ui/core" export default function Cart() { const [itemNumber, setItemNumber] = useState ...

Troubleshooting the issue with a styled subcomponent in React using Styled Components

Recently, I've delved into React and have been experimenting with creating a Modal component using styled components. My goal is to achieve a similar effect to Framer Motion's motion.div, but utilizing styled components instead. Currently, I hav ...

Tips for centering the InputLabel in Material UI?

Upon loading the page, I am looking to have the InputLabel appear as shown in the second picture. However, I haven't been able to find any InputLabel props that achieve this. I attempted using the focused prop, but it didn't give me the desired o ...

We're sorry, the page you are looking for cannot be found. Error 404: Page Not Found

Good day: I am encountering this Django error when attempting to update a "User": Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/users/modify/ Using the URLconf defined in APPNAME.urls, Django attempted these URL pa ...

The image fails to upload on the server

I am encountering an issue with Laravel 5.8 while trying to upload a file to the server using ajax. For some reason, the input file is not being sent along with the other data. The hasFile() method always returns false and input::file() returns null in th ...

Is there a way to position one DIV behind another?

Hey, I'm working on my first project and running into some trouble with divs. I'm trying to position the firework behind the central text but can't figure it out. Can anyone lend a hand? I need to add more details in order to submit the que ...

Unable to add to content that is generated dynamically

Upon loading the page, I noticed that the #navbarUsername field remains empty while all other scripts below it run correctly. Despite attempting to use $(document).on('ready', '#navbarUsername', function () {..., this did not resolve th ...

Steps to alter background image and adjust its height upon function activation

I am working on a search page with an advanced search option that only certain users can access. I need the height of my div to increase accordingly and also change the background image to a larger size when the advanced search is selected. How can I make ...

Angular 14's "rootItem" animation trigger was created with the following alerts: - The properties listed below are not animatable: overflow

Upon upgrading to Angular 14, I encountered this warning. The properties mentioned are not actually used in my animations. [Error in console][1] The animation triggers "rootItem" has been built with the following warnings: - The following provided propert ...

Continue making ajax calls after the function has been executed

I have encountered a problem where I need to ensure that the function llamadaEntrante() is executed before the confirm() alert, even when it's called after. Unfortunately, I haven't been able to make this work. Any ideas? Below is the code snipp ...

Django update button to change form status

Each row in the table contains a button with the unique identifier of the element. Clicking on the button will populate the form with the corresponding data. I suspect that there is an issue with the renderer, as it clears the form and I'm unsure how ...

Adding an image to an HTML page

I am working on an HTML page and need to insert an image. Here is the code I currently have: <img src="../Images/logo.jpg" alt="Logo" height="50"> I chose "../Images/logo.jpg" as the source because my logo.jpg is located two levels up from the curr ...

Using jQuery's AJAX method to serialize and upload form data

I'm currently facing an issue with uploading an image through an HTML form. The form gets added to a div when a user clicks on an item, and here's how the code looks: $("#editavatar").click(function(){ $(".rightdisplay").html('<form ...

Add the outcome of an AJAX request to a pre-existing list

I am currently working on a form that generates tweets. These tweets are displayed in an unordered list format for each user. My goal is to dynamically add newly created tweets to the list without needing to refresh the page, using AJAX. Could you please ...