我有一个宽度为 360px
的小面板。在面板的顶部,有一个由当前 3 个按钮组成的导航栏(尽管数量无关紧要)。我希望按钮填满 div 的整个宽度,并根据里面单词的长度占用或多或少的空间。目前,我只知道如何将按钮的宽度设置为一个值,但是如果我添加一个按钮,则需要手动更改这些值。
这就是我现在拥有的,但显然它看起来很糟糕。如何让第一个按钮更窄,第二个按钮更宽,并让所有三个按钮一起占据面板的整个宽度?
这是我的代码:
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>
关于html - 让一组按钮填满父 div 的整个宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40766075/