html - 让一组按钮填满父 div 的整个宽度

标签 html css button width navbar

我有一个宽度为 360px 的小面板。在面板的顶部,有一个由当前 3 个按钮组成的导航栏(尽管数量无关紧要)。我希望按钮填满 div 的整个宽度,并根据里面单词的长度占用或多或少的空间。目前,我只知道如何将按钮的宽度设置为一个值,但是如果我添加一个按钮,则需要手动更改这些值。

what it currently looks like

这就是我现在拥有的,但显然它看起来很糟糕。如何让第一个按钮更窄,第二个按钮更宽,并让所有三个按钮一起占据面板的整个宽度?

这是我的代码:

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>TEST</title>
    <link type="text/css" rel="stylesheet" href="test.css"/>
</head>
<body>
    <div class="panel">
        <ul class="nav">
            <li class="buttons">SHORT</li>
            <li class="buttons">LOOOOOOOOOOONG</li>
            <li class="buttons">...</li>
        </ul>
    </div>
</body>
</html>

CSS:

.panel {
    background-color: grey;
    width: 360px;
    height: 600px;
    position: relative;
    border: 1px solid black;
}

.nav {
    padding: 0;
    margin: 0;
}

.buttons {
    float: left;
    display: block;
    padding: 0px 20px;
    height: 40px;
    width: 60px;
    background-color: #666666;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
    text-align: center;
    line-height: 40px;
}

最佳答案

我会为此选择 flexbox 解决方案:

.panel {
  background-color: grey;
  width: 360px;
  height: 600px;
  position: relative;
  border: 1px solid black;
}
.nav {
  padding: 0;
  margin: 0;
  
  /* add the following */
  width:100%;
  display:flex; 
  flex-direction:row;
}

.buttons {
  display: block;
  padding: 0px 20px;
  height: 40px;
  background-color: #666666;
  border-right: 1px solid black;
  border-bottom: 1px solid black;
  text-align: center;
  line-height: 40px;
  
  /* remove your width and float and add the following */
  flex-grow:1;
}

/*optional*/
.nav li:last-child {border-right:none;}
<div class="panel">
  <ul class="nav">
    <li class="buttons a">SHORT</li>
    <li class="buttons b">LOOOOOOOOOOONG</li>
    <li class="buttons c">...</li>
  </ul>
</div>

More information about flex

A complete guide to flexbox

关于html - 让一组按钮填满父 div 的整个宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40766075/

相关文章:

javascript - jQuery - 允许插入文本的组合框

html - html代码中的iframe无法加载网站

css - 使链接具有 100% 的宽度

javascript - 如何在tinyMCE事件编辑器弹出窗口中的自定义按钮上应用CSS

jquery - 如何附加一个按钮,然后告诉该按钮删除 html 元素?

c# - 设置 Material 设计 :PackIcon code behind

javascript - anchor 标记下载属性不起作用 :Bug in Chrome 35. 0.1916.114

html - 调整 Web 浏览器 HTML 大小时文本被压扁 | CSS

javascript - wkhtmltopdf 第二页的页边距

javascript - 单击内容后如何使下拉按钮保持打开状态?