css - 自动调整导航菜单

标签 css

我想创建一个导航菜单,根据菜单中内容(按钮)的数量自动调整其宽度

例如:

导航菜单将有 4 个按钮;每个按钮都有一个 'min-width:25px' 和一个 max-'width:100px',具体取决于其中的文本。

因此,如果所有 4 个按钮中的文本数量相同并且都等于 50px,则包含其中所有按钮的导航菜单 DIV 应自动调整为 200px。如果我随后添加宽度为 65px 的第 5 个按钮,导航菜单 DIV 应自动调整为 265px

问题

我的按钮可以工作(它们会根据其中的文本量自动调整宽度),但是,我的导航菜单 (nav-top) 不会自动调整。我不确定我做错了什么,但我猜这是一个简单的修复。

DIV 和所有按钮的 HTML:

   <div id="nav-top" >

    <ul class="top-nav">
     <li><a href="">Home </a></li>
     <li><a href="">About Us </a></li>
     <li><a href="">Apply </a></li>
     <li><a href="">Contact </a></li>
    </ul>

   </div><!--nav-top-->

我的 CSS:

/* Holds all the buttons */
#nav-top {
    min-width:200px;
    max-width:900px;
    height:35px;
    position:relative;
    background-color:#555;
    top:7px;

}


.top-nav {
    list-style:none;
    padding:0px;
    margin:0px;
    text-align:left;

}


.top-nav a {
   display: block;
   background-color: #888;
   color: #000;
   text-decoration: none;
   min-width:25px;
   max-width:100px;
   float:left;
   padding:7px;

}

.top-nav a:hover
{
text-decoration: none;
color: #fff;
background-color: #000;
}

最佳答案

在这里可以使用表格布局样式。具有 display:table 的元素将 flex 以适合其子元素 table-cell

ul.top-nav{    
    display:table;
    max-width:900px;
    padding:0;
    margin:0;
}
ul.top-nav li {
   display: table-cell;
}

查看我的 example JSFiddle

关于css - 自动调整导航菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19874085/

相关文章:

html - 选择选项时,部分选定文本被隐藏

css - Facebook 点赞框 API : Unable to alter height

javascript - CSS在彼此下获取图片

html - 如何使用Html5的details和summary标签隐藏和展开表格中的整行?

html - <p> 标签的使用

html - 从一个页面移动到另一个页面时,导航菜单会闪烁,仅在 Chrome 中

html - 使用顶部的元素底部的粘性元素?

html - 摆脱表头第一个元素的右边界的最有效方法是什么?

html - 如何在纯CSS中使伪元素具有相同的高度和宽度?

html - CSS 为什么上划线在悬停时不会改变颜色和样式?