Home > Software design >  Set `width: auto` in flex-direction: column;
Set `width: auto` in flex-direction: column;

Time:10-05

I have div1 with flex-direction: column. Inside that div1 I want to have another div2. I'll be populating that div2 with words of different lengths and I want the width to be auto(self-adjustable). But width: auto doesn’t work with flex-direction: column. And I want to have div2 aligned to the left.

.parent {
  background: lightblue;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.child {
  display: flex;
  border: 2px solid green;
  border-radius: 4px;
  padding: 10px;
  ///////
  width: auto;
}
<div class='parent'>
  <div class='child'>
    <span>
      Some text
    </span>
  </div>
 </div>

I want the same behavior as if flex-direction would be set to row. Just like this:

.parent {
  background: lightblue;
  padding: 10px;
  display: flex;
  flex-direction: row;
}
.child {
  display: flex;
  border: 2px solid green;
  border-radius: 4px;
  padding: 10px;
}
<div class='parent'>
  <div class='child'>
    <span>
      Some text
    </span>
  </div>
 </div>

P.S. Cannot use width: max-content; and width: min-content;

CodePudding user response:

Place align-items:flex-start on the parent.

.parent {
  background: lightblue;
  padding: 10px;
  display: flex;
  flex-direction: column;
align-items: flex-start;
}
.child {
  display: flex;
  border: 2px solid green;
  border-radius: 4px;
  padding: 10px;
}
<div class='parent'>
  <div class='child'>
    <span>
      Some text
    </span>
  </div>
 </div>

Alternatively, align-self:start on the child

.parent {
  background: lightblue;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.child {
  display: flex;
  border: 2px solid green;
  border-radius: 4px;
  padding: 10px;
  align-self: start;
}
<div class='parent'>
  <div class='child'>
    <span>
      Some text
    </span>
  </div>
</div>

  • Related