首页 > 解决方案 > 设置 `width: auto` 在 flex-direction: column;

问题描述

div1flex-direction: column。在那个 div1 里面我想要另一个div2. 我将用不同长度的单词填充该 div2,并且我希望它widthauto(可自我调整的)。但width: auto不适用于flex-direction: column. 而且我想div2 向左对齐

.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>

flex-direction我想要与设置为相同的行为row像这样:

.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>

PS 不能使用width: max-content;width: min-content;

标签: htmlcssflexboxwidth

解决方案


放在align-items:flex-start父母身上。

.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>

或者,align-self:start在孩子身上

.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>


推荐阅读