Auto width of flex column

2020-08-17 06:58发布

问题:

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



标签: css flexbox