使flex div的宽度适应内容,但在单独的行中弯曲项目

时间:2018-04-11 05:31:21

标签: html css flexbox

<div class="flex_container">
  <div class="flex_item1">Item</div>
  <label for="" class="flex_item1">I am a Label</label>

  <!-- This whole block needs to be in a new line -->
  <div class="flex_item2">Item 2</div>
  <label for="" class="flex_item2">I am a Label 2</label>
</div>

CSS:

.flex_container{
    display: inline-flex;
    align-items: center;
}

.flex_item1{
  background-color: red;
}

.flex_item2{
  background-color: yellow;
}

小提琴https://jsfiddle.net/f6atroh2/9/

我希望flex_container div的宽度适应flex_item的内容。我已经看到人们使用display: inline-flex,但这使得内部div不会分开,这是我想要的。

1 个答案:

答案 0 :(得分:2)

您需要将html更新为此。

 <div class="flex_container">
   <div class="temp">
      <div class="flex_item1">Item</div>
      <label for="" class="flex_item1">I am a Label</label>
 </div>
  <!-- This whole block needs to be in a new line -->
<div class="temp">
   <div class="flex_item2">Item 2</div>
   <label for="" class="flex_item2">I am a Label 2</label>
  </div>
</div> 

并将css更新为此。

.flex_container{

    display: inline-flex;
    align-items: center;
    flex-direction:column;
}

.flex_item1{
  background-color: red;
 }

.flex_item2{
   background-color: yellow;
 }

.temp{

  display:flex;
  flex-direction:row;
 }