Search code examples
htmlcssbuttonwidthnavbar

Make a group of buttons fill the whole width of the parent div


I have a small panel with a width of 360px. At the top of the panel, there is a navigation bar consisting of currently 3 buttons (the number should not matter though). I want the buttons to fill out the whole width of the div and take up more or less space depending on the length of the word inside. Currently, I only know how to set the width of the buttons to a value, but then if I add a button the values would need to be changed manually.

what it currently looks like

this is what I have now, but obviously it looks horrible. How can I make the first button less wide, the second button wider and have all three buttons together take up the whole width of the panel?

Here is my code:

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;
}

Solution

  • I would go with a flexbox solution for this:

    .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