如何在没有中心标签的情况下居中菜单项?

时间:2016-12-23 12:10:35

标签: html css

我发现了这个 JS FIDDLE ,它可以通过全宽下拉来完成我需要的工作。

问题: 我试图将按钮准确地放在中间,并以此填充宽度下拉菜单为中心。出于某种原因,当我使用html <center>标签时,它不起作用。

$(document).ready(function() {
    //variable where currentAnchor is stored
    var currentSection = 0;
    // hides the submenu as soon as the DOM is ready
    $('#submenu').hide();
    // toggles the submenu on clicking the noted link  
    $('#menu li a').click(function() {
        
        // remove active class
        $('#menu li a').removeClass('active');
        // add active class
        $(this).addClass('active');
        
        var href = $(this).attr('href');
        //hide all submenus
        $('#hidden>ul').hide();
        
        //show one particular menu
        $(href).show();

        
        //logic for hiding and showing submenu
        if(currentSection == 0){
            $('#submenu').slideToggle(200);
            currentSection = href;
        } else if(currentSection == href){
             $('#submenu').slideToggle(200);
             currentSection = 0;    
        } else{
            currentSection = href;
        }
        return false;
    });
});
#menu li {
    display: inline-block;
}
#menu li a {
    padding: 10px 20px;
    background: #e45740;
    color: #FFF;
    text-decoration: none;
    height: 50px;
    line-height: 50px;
}
#submenu {
    display: block;
    width: 100%;
    padding: 10px;
    background: #555;
    color: #FFF;
}
#submenu #hidden {
}

* {
    font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="menu">
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
</ul>

<div id="submenu" style="display:none;">
   <div id="hidden">
        <ul id="one">
            <li>One</li>
        </ul>
        <ul id="two">
            <li>Two</li>
        </ul>
        <ul id="three">
            <li>Three</li>
        </ul>       
    </div>
</div>

2 个答案:

答案 0 :(得分:2)

你必须写下面的css来制作中心的按钮

#menu{
    margin: 0 auto;
    display: table;
}

我希望它有效......

答案 1 :(得分:0)

假设您的HTML结构与提供的小提琴链接相同,您只需要将text-align:center;添加到您的ul中,如下所示:

#menu {
   text-align: center; 
}