gpt4 book ai didi

html - 让 child 适应 parent

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:59 26 4
gpt4 key购买 nike

我在底部嵌套了带有文本的 flex 元素。顶部元素具有小于文本的固定宽度:

.list-header {
display: flex;
width: 150px;
height: 80px;
background-color: #ececec;
}

.list-component {
display: flex;
flex: 1;
padding-left: 24px;
padding-right: 24px;
}

.header-container {
display: flex;
flex: 1;
}

.header-text {
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
}

span {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
<div class="list-header">
<div class="list-component">
<div class="header-container">
<div class="header-text">
<span>long long long long long long text</span>
</div>
</div>
</div>
</div>

我可以通过对所有元素应用 overflow: hidden; 来解决这个问题:

.list-header {
display: flex;
width: 150px;
height: 80px;
background-color: #ececec;
}

.list-component {
display: flex;
flex: 1;
padding-left: 24px;
padding-right: 24px;
overflow: hidden;
}

.header-container {
display: flex;
flex: 1;
overflow: hidden;
}

.header-text {
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
}

span {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
<div class="list-header">
<div class="list-component">
<div class="header-container">
<div class="header-text">
<span>long long long long long long text</span>
</div>
</div>
</div>
</div>

但我不太喜欢这个解决方案。

有没有办法只使用 flex 属性来修复它?

最佳答案

flex 元素的初始设置是 min-width: auto。这意味着 flex 元素不能短于其内容的宽度。

文本元素上有 white-space: nowrap。因此,所有 flex 元素的祖先都必须扩展(以多米诺骨牌效应)以适应文本的长度。

受影响的 flex 元素是:

  • .list-component
  • .header-container
  • .header-text

因此,为了防止文本溢出主容器,需要覆盖默认的min-width: auto。 flexbox 规范提供了两种方法来做到这一点:

  1. 为 flex 元素添加min-width: 0
  2. overflow 添加到 flex 元素中,除了 visible 之外的任何值。 (这就是为什么您能够通过添加 overflow: hidden 来解决问题。它实际上是一个干净有效的解决方案。)

这个行为在这篇文章中有更详细的解释:

.list-header {
display: flex;
width: 150px;
height: 80px;
background-color: #ececec;
}

.list-component {
display: flex;
flex: 1;
padding-left: 24px;
padding-right: 24px;
min-width: 0; /* NEW */
}

.header-container {
display: flex;
flex: 1;
min-width: 0; /* NEW */
}

.header-text {
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0; /* NEW */
}

span {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
<div class="list-header">
<div class="list-component">
<div class="header-container">
<div class="header-text">
<span>long long long long long long text</span>
</div>
</div>
</div>
</div>

关于html - 让 child 适应 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44826555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com