如何在没有固定宽度的容器中内联显示多个div?

时间:2015-09-12 13:47:28

标签: html css3 page-layout

我在导航栏上工作,需要并排显示多个div。但是父div没有固定的宽度。只是一些填充。所以问题是如何实现这一目标?



.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>
&#13;
&#13;
&#13;

这四个彩色div必须是内联的。

1 个答案:

答案 0 :(得分:2)

您可以在display: flex元素上使用#container。将display设置为flex的容器内元素的默认方向为row。因此元素从左到右。

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;