css 子元素在溢出时不拉伸

fd3cxomn  于 2023-04-23  发布在  其他
关注(0)|答案(3)|浏览(175)

我有一个容器div带有overflow auto。当一个子元素有长文本时,它会溢出容器,导致它显示x-scroll。到目前为止没有问题。问题是子元素没有随着容器宽度拉伸,包括可用的滚动,导致它在滚动容器时看起来被切断:

.flex-col {
  flex-direction: column;
}

.h-full {
  height: 100%;
}

.flex {
  display: flex;
}

.container {
  overflow: auto;
  resize: horizontal;
  min-width: 10rem;
  max-width: 25rem;
}

.item.selected {
  background-color: green;
  color: red;
}

.item {
  white-space: nowrap;
}
<div class="flex flex-col h-full">
  <div class="h-full container">
    <div class="flex p-2 items-center item selected">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">1Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
    <div class="flex p-2 items-center item">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">2Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
    <div class="flex p-2 items-center item">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">3Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
  </div>
</div>

https://jsfiddle.net/690j7bsw/
我错过了什么?
谢谢!

zed5wv10

zed5wv101#

这是在使用whitespace-nowrapoverflow属性时非常常见的问题。
要解决这个问题,您需要将display: flex更改为display: inline-flex
就像这样:

.flex {
  display: inline-flex;
}

这是因为即使文本没有换行,块元素也会占用100%的宽度。内联元素不是这样的。它们总是占用内容的宽度,这正是我们在这里利用的。
注意:您可以将类flex重命名为inline-flex,以使其更直观。
https://jsfiddle.net/3xo0gq1p/

b1zrtrql

b1zrtrql2#

selected 类添加到具有长文本的div-element中
接下来将CSS选择器调整为.item .selected {...}

5q4ezhmt

5q4ezhmt3#

只需将width: fit-content;添加到.item

.flex-col {
  flex-direction: column;
}

.h-full {
  height: 100%;
}

.flex {
  display: flex;
}

.container {
  overflow: auto;
  resize: horizontal;
  min-width: 10rem;
  max-width: 25rem;
}

.item.selected {
  background-color: green;
  color: red;
}

.item {
  white-space: nowrap;
  width: fit-content; /* 👈 */
}
<div class="flex flex-col h-full">
  <div class="h-full container">
    <div class="flex p-2 items-center item selected">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">1Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
    <div class="flex p-2 items-center item">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">2Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
    <div class="flex p-2 items-center item">
      <div class="flex items-center">-</div>
      <div class="whitespace-nowrap">3Loooooooooooooong text that does not wrap.... aaaaaaaaaa sssssssss ddddddddd</div>
    </div>
  </div>
</div>

相关问题