Auto width of flex column

China☆狼群 提交于 2020-01-03 08:49:12

问题


How can I set the width of first flex column so that its width is only the size of its content? http://codepen.io/anon/pen/rrKkOW

<div class="flex">
  <div class="inside inside-left">Left</div>
  <div class="inside inside-right">RIght</div>
</div>

.flex {
  display: flex;
}

.inside {
  flex: 1;
  border: 1px solid #000;
}

Setting width: auto doesn't work... Something like flex-basis: content would be nice to have :)


回答1:


Don't give that column flex:1 as it will expand to take up as much room as is permitted.

In fact, don't give it any flex value at all and it will default to width:auto.

.flex {
  display: flex;
}
.inside {
  border: 1px solid #000;
}
.inside-right {
  flex: 1;
  background:#c0ffee;
}
<div class="flex">
  <div class="inside inside-left">Left</div>
  <div class="inside inside-right">RIght</div>
</div>

<div class="flex">
  <div class="inside inside-left">Left Left Left LeftLeft Left</div>
  <div class="inside inside-right">RIghtRIghtRIght RIght</div>
</div>

<div class="flex">
  <div class="inside inside-left">Left Left Left LeftLeft LeftLeft Left Left LeftLeft Left</div>
  <div class="inside inside-right">RIghtRIghtRIght RIghtRIghtRIght</div>
</div>

EDIT: It seems the intention was to have every "left" element be the same size.

This is not possible with flexbox but CSS Tables can achieve this.

.row {
  display: table-row;
}
.inside {
  display: table-cell;
  border: 1px solid grey;
}
.inside-left {
  background: lightgreen;
}
<div class="row">
  <div class="inside inside-left">Left</div>
  <div class="inside inside-right">RIght</div>
</div>

<div class="row">
  <div class="inside inside-left">Left Left Left LeftLeft Left</div>
  <div class="inside inside-right">RIghtRIghtRIght RIght</div>
</div>

<div class="row">
  <div class="inside inside-left">Left Left Left LeftLeft LeftLeft Left Left LeftLeft Left</div>
  <div class="inside inside-right">RIghtRIghtRIght RIghtRIghtRIght</div>
</div>



回答2:


You have to restructure your HTML a bit to achieve what you want:

.flex {
  display: flex;
}
.inside {
  border: 1px solid #000;
}
.flex-grow {
  flex: 1;
}
.inside-right {
  background:#c0ffee;
}
<div class="flex">
  <div>
    <div class="inside">Left</div>
    <div class="inside">Left Left Left LeftLeft Left</div>
    <div class="inside">Left Left Left LeftLeft LeftLeft Left Left LeftLeft Left</div>
  </div>
  <div class="flex-grow">
    <div class="inside inside-right">Right</div>
    <div class="inside inside-right">RIghtRIghtRIght RIght</div>
    <div class="inside inside-right">RIghtRIghtRIght RIghtRIghtRIght</div>
  </div>
</div>



回答3:


If you want each column to be as wide as its content you need to use align-item: flex-start check this link here



来源:https://stackoverflow.com/questions/40018606/auto-width-of-flex-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!