htmlcsspage-layout

How to display multiple divs, inline within a container without fixed width?


I'm working on a navigation bar that needs to display multiple divs side by side. But the parent div doesn't have a fixed width. Just some padding. So the question is how can I achieve this?

.nav {
  width: 100%;
  height: 50px;
}

.nav ul {
  width: 100%;
  height: 50px;
}

.nav ul li {
  display: inline;
  list-style-type: none;
  background: gray;
  padding: 10px 30px;
  margin: 0 10px;
  height: 100%;
  position: relative;
}

#container {
  position: absolute;
  left: 0;
  top: 100%;
  background: black;
  padding: 10px;
}

#container .category {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 80px;
}
<div class="nav">
  <ul>
    <li>AB
      <div id="container">
        <div class="category" style="background: #4285f4;"></div>
        <div class="category" style="background: #ea4335;"></div>
        <div class="category" style="background: #fbbc05;"></div>
        <div class="category" style="background: #34a853;"></div>
      </div>
    </li>
    <li>CD</li>
    <li>EF</li>
    <li>GH</li>
  </ul>
</div>

Those four colored divs must be inline.


Solution

  • You can use display: flex on the #container element. The default direction for the elements inside a container with display set to flex is row. So the elements go from left to right.

    .nav {
        width: 100%;
        height: 50px;
    }
    
    .nav ul {
        width: 100%;
        height: 50px;
    }
    
    .nav ul li {
        display: inline;
        list-style-type: none;
        background: gray;
        padding: 10px 30px;
        margin: 0 10px;
        height: 100%;
        position: relative;
    }
    
    #container {
        position: absolute;
        left: 0;
        top: 100%;
        background: black;
        padding: 10px;
        display: none;
    }
    
    .nav li:hover > #container {
        display: flex;
    }
    
    #container .category {
        position: relative;
        display: inline-block;
        width: 50px;
        height: 80px;
    }
    <div class="nav">
      <ul>
        <li>AB
          <div id="container">
            <div class="category" style="background: #4285f4;"></div>
            <div class="category" style="background: #ea4335;"></div>
            <div class="category" style="background: #fbbc05;"></div>
            <div class="category" style="background: #34a853;"></div>
          </div>
        </li>
        <li>CD</li>
        <li>EF</li>
        <li>GH</li>
      </ul>
    </div>