div堆栈的动态宽度

时间:2016-07-07 15:42:19

标签: html css

我有一堆div框如下:

enter image description here

我的目标是:框BC的宽度应相同,框A的宽度应为BC。应显示每个框的内容,不带换行符。它们应按照图片排列。框ABC的内容是动态创建的。

我几乎实现了这一点(请参见底部代码),将这3个框放在display:inline-block中,并为框width:50%B设置C。这在某些情况下效果很好,但是当框B的内容太大时,我得到了这个结果:

enter image description here

我理解结果,因为总宽度由方框A确定,方框Bwidth: 50%。但是,我希望框B得到拉伸,这样就不需要换行了,如下所示:

enter image description here

我怎样才能做到这一点?

这是生成图像的代码(请参阅此jsFiddle):

<style>
.container{
  display: inline-block;
  text-align:center;
  padding: 5px;
  border:dashed red;
}

.head{
  border:solid;
  background-color: yellow;
  padding: 30px;
}



.item{
  width: 50%;
  display: inline-block;
  border:solid;
  box-sizing: border-box;
  padding: 5px;
}

.red{
  background-color: red;
 }

 .green{
   background-color: green;
 }
}
</style>
<div class="container">
 <div class="head">
 A
 </div>

 <div>
   <div class="item red">
    B
   </div><!--
   --><div class="item green">
   C
   </div> 
 </div>

</div>

1 个答案:

答案 0 :(得分:2)

结构和弹性箱的微小变化可以做到这一点。

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.container {
  display: inline-flex;
  text-align: center;
  padding: 5px;
  border: dashed red;
  flex-wrap: wrap
}
.head {
  border: solid;
  background-color: yellow;
  flex: 0 0 100%;
  padding: 30px;
}
.item {
  width: 50%;
  display: inline-block;
  border: solid;
  box-sizing: border-box;
  padding: 5px;
}
.red {
  background-color: red;
}
.green {
  background-color: green;
}
<div class="container">
  <div class="head">
    Very very long text
  </div>


  <div class="item red">
    Also very very long text
  </div>
  <div class="item green">
    C
  </div>
</div>

或者......如果你想把底部div包裹起来......还是flexbox

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.container {
  display: inline-flex;
  text-align: center;
  padding: 5px;
  border: dashed red;
  flex-wrap: wrap
}
.head {
  border: solid;
  background-color: yellow;
  flex: 0 0 100%;
  padding: 30px;
}
.wrap {
  flex: 0 0 100%;
  display: flex;
}
.item {
  width: 50%;
  display: inline-block;
  border: solid;
  box-sizing: border-box;
  padding: 5px;
}
.red {
  background-color: red;
}
.green {
  background-color: green;
}
}
<div class="container">
  <div class="head">
    Very very long text
  </div>

  <div class="wrap">
    <div class="item red">
      Also very very long text
    </div>
    <div class="item green">
      C
    </div>
  </div>

</div>