css - flexbox中每个元素根据其内容占用大小,为什么有的时候会把内容传给另一行?

标签 css flexbox

我正在尝试一些简单的事情,但我不知道自己做错了什么。我有 2 篇文章,我想尊重第二篇文章的大小,文本放在另一行。我希望第一篇的内容放在其他行,但是第二篇的内容却占据了不显示在第二行的必要。

这道题是为了多了解一点flexbox,并得到一个使用它的解决方案。

section {
  height: 400px;
  width: 100%;
  display: flex;
  flex-direction: row;
  order: solid 1px black;
}

.box1 {
  background: red;
}

.box2 {
  background: yellow;
}
<section>
  <article class="box1">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum dolore quae at provident libero eum, nulla laborum eaque aliquid quos modi, ex, qui officia est possimus. Maiores asperiores sunt quo.
  </article>
  <article class="box2">
    caja 2
  </article>
</section>

enter image description here

最佳答案

您可以通过添加 flex-shrink:0 来避免第二个 div 收缩:

The flex-shrink CSS property specifies the flex shrink factor of a flex item. Flex items will shrink to fill the container according to the flex-shrink number, when the default size of flex items is larger than the flex container.ref

section{
  height:400px;
  width:100%;
  display:flex;
  flex-direction:row;

  border: solid 1px black;
}

.box1{
  background:red;
}
.box2{
  background:yellow;
  flex-shrink:0;
}
<section>
  <article class="box1">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum dolore quae at provident libero eum, nulla laborum eaque aliquid quos modi, ex, qui officia est possimus. Maiores asperiores sunt quo.
  </article>
  <article class="box2">
  this one will be kept in one line
  </article>
</section>

所以如果没有 flex 收缩,基本上两个元素都会溢出容器:

section{
  height:400px;
  width:100%;
  display:flex;
  flex-direction:row;

  border: solid 1px black;
}

.box1{
  background:red;
  flex-shrink:0;
}
.box2{
  background:yellow;
  flex-shrink:0;
}
<section>
  <article class="box1">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum dolore quae at provident libero eum, nulla laborum eaque aliquid quos modi, ex, qui officia est possimus. Maiores asperiores sunt quo.
  </article>
  <article class="box2">
  caja 2
  </article>
</section>

因为默认情况下 flex-shrink 设置为 1 两个元素将同样收缩以适应它们的父容器,因此您的内容将被移动到一个新行。这里的技巧是通过禁用第二个元素的收缩效果来只允许第一个元素收缩。

这是一个useful link更好地理解 flexbox 算法以及 flex-shrink 如何影响布局。

关于css - flexbox中每个元素根据其内容占用大小,为什么有的时候会把内容传给另一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51584447/

相关文章:

javascript - 无休止地旋转图像/div(跨浏览器)

html - 为什么按钮内有多余的水平填充(仅限 Firefox)?

html - 如何让网站的内容居中?

html - 使用 flex 将元素定位到 div 的底部

html - Inline-Flex 与垂直对齐混淆

html - 列表项左侧的圆盘显示在底部

html - 如何扩展一个div以填充整个页面

html - Angular 。使子级 100% 宽度为 flex 父级

html - Flexbox 对齐底部

css - 遇到 Flexbox 问题 2 列 3 元素