如何让孩子在一个固定的容器中漂浮在并排元素内?

时间:2016-04-07 15:12:19

标签: css

我有这种情况:

HTML:

<div class="container0">
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  <div>
<div>

的CSS:

.container0 {
  width:600px; /*needed*/
}

.item {
  border: solid;
  background: yellow;
  float: left;
  position: relative;
  width: auto; /*needed, should be width of the contents*/
}

.subitens {
    background: red;
    padding: 10px;
}
.child {
    background: blue;
    border: solid;
    width: 100px; /*needed*/
    height: 100px; /*needed*/
    float: left;
}

http://jsfiddle.net/tombrito/gx7kL330/6/

我希望.item元素并排,而.child元素将浮动以适应空间(600px)。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你正在寻找这样的东西吗?

.container0 {
  width:600px; /*needed*/
  display: flex;
}

.item {
  display: flex;
  flex: 1;
  border: solid;
  background: yellow;
}

.subitens {
  display: flex;
  flex: 1;
  background: red;
  padding: 10px;
}
.child {
  flex: 1;
  border: solid;
  width: 100px;
  height: 100px;
}
.child {
  background: blue;
}
<div class="container0">
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
<div>

以下是我的第一个示例非flex,它实际上效果很好,因为child元素具有固定的width

.container0 {
  width:600px; /*needed*/
  white-space: nowrap;
}
.item {
  border: solid;
  background: yellow;
  display: inline-block;
  vertical-align: top;
  position: relative;
  box-sizing: border-box;
}
.subitens {
  background: red;
  padding: 10px;
  box-sizing: border-box;
}
.child {
  border: solid;
  width: 100px;
  height: 100px;
  float: left;
  box-sizing: border-box;
}
.child {
  background: blue;
}
<div class="container0">
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
  <div class="item">
    <div class="subitens">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
  </div>
<div>