即使设置 min-width:0 之后,Flex 子容器也会溢出父容器?

unp*_*ble 2 html css flexbox

子弹性项目溢出了父容器的宽度。我也尝试设置 min-width:0 但仍然不起作用。

这是我的 HTML 和 CSS 代码:

.parent{
  display: flex;
  border: 2px solid red;
}

.child1{
  background: cyan;
  height: 40px;
  width: 40px;
  flex-shrink: 0;
}

.child2 {
  background: pink;
  height: 20px;
  width: 20px;
}

.child3 {
  background: yellow;
  height: 20px;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)
<div class='parent'>
  <div class='child1'>1</div>
  <div>
    <div class='child2'>2</div>
    <div class='child3'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus sagittis odio, ac pulvinar tortor sagittis et. In hac habitasse platea dictumst. Phasellus ut velit dolor. Vestibulum pulvinar orci libero, in aliquet arcu auctor non. Morbi volutpat elit id lacus cursus, at imperdiet tellus eleifend. Morbi euismod vehicula urna, sed pretium felis ullamcorper vitae. Nunc at ligula a odio eleifend convallis eget sed orci. Praesent fermentum, sem in congue tempus, ex diam suscipit neque, in ullamcorper orci erat eu orci.</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的动机是防止child3溢出父容器并在溢出时显示省略号(...)。

任何帮助表示赞赏。

chi*_*eek 5

您发布的内容存在一些问题,但不用担心,我们可以解决您的问题。

\n

什么是弹性,什么不是

\n

首先让我们看看您的标记:

\n

.parent是一个具有 的元素display: flex。根据您的命名,我们可能会错误地假设它的孩子是:

\n
    \n
  • .child1,
  • \n
  • .child2, 和
  • \n
  • .child3。
  • \n
\n

\xe2\x80\xa6 但事实并非如此。

\n

的孩子.parent实际上是:

\n
    \n
  • .child1, 和
  • \n
  • 无阶级的div。
  • \n
\n

无类div没有为其设置样式,因此.child2和.child3不位于弹性盒上下文中。因此,您的min-width: 0on.child3并不能解决您的问题,因为该解决方案仅适用于 Flex 子项。

\n

min-width在正确的上下文中应用

\n

首先,让我们给这个孩子上div一堂课:.foo。

\n

.foo本身有一个块显示,但目前它允许内容(in .child3)溢出。我们要防止溢出的正是这个元素:

\n
.foo {\n  min-width: 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这应该就是您所需要的。看来您已经熟悉我们为什么要使用它min-width来帮助解决此问题,但以防万一您可以在CSS 技巧:Flexbox 和截断文本中阅读相关内容。

\n

解决方案

\n

下面是所有内容的汇总。

\n

\r\n
\r\n
.foo {\n  min-width: 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\r\n
.parent {\n  display: flex;\n  border: 2px solid red;\n}\n\n.foo {\n  min-width: 0;\n  outline: 1px solid rebeccapurple;\n}\n\n.child1 {\n  background: cyan;\n  height: 40px;\n  width: 40px;\n  flex-shrink: 0;\n}\n\n.child2 {\n  background: pink;\n  height: 20px;\n  width: 20px;\n}\n\n.child3 {\n  background: yellow;\n  height: 20px;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  max-width: 100%;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n