gpt4 book ai didi

css - 文本开始溢出时如何使用动态替换文本?

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:31 26 4
gpt4 key购买 nike

如果我在页面加载时(但在设计时不知道)有三个文本字符串,例如:

  1. 全文可能有点长。
  2. 部分文字较短。
  3. 小文本。

我如何将文本放置在某些 HTML 元素(div 或 span 很好)中而不换行,例如当用户执行某些调整 HTML 元素大小的操作时,最长的文本是首选,但如果文本会溢出,切换到下一个不会溢出的最短文本?调整小于最小文本的大小将隐藏任何溢出(即 HTML 元素将溢出:隐藏)。

最佳答案

只要您愿意限制高度,您就可以使用 CSS 做到这一点。由于您只需要 1 行文本,因此将高度限制为 1em 似乎不是不合理的限制。

当你 float 一个元素时,当第一行没有足够的空间时,它会流动到下一行。此解决方案中的每一行都有两个元素:

  1. 一个宽度为 1px 的 breaker 元素。不幸的是,根据我的测试,这个元素必须有一定的宽度才能参与流程。
  2. 要显示的文本。

文本必须按从短到长的顺序排列,并且不得有透明背景。使用透明背景可以让较短的文本显示出来。

.container {
white-space: nowrap;
height: 1em; /* Must be fixed height */
width: 100%; /* Or any width you want */
overflow: hidden; /* Make sure that the elements that are bumped down don't show */
border: 1px solid red; /* For example only */
}

.container p {
position: relative; /* Relative to allow shifting elements up */
float: left;
left: 0;
padding: 0;
margin: 0;
height: 1em; /* Text block must be fixed height */
background-color: white; /* Text block must be opaque */
}

.container .break {
float: left;
clear: left;
width: 1px;
height: 1em; /* Must be the same height as a text block */
}

/* Shift each longer text block up to sit atop the first one */
.container p:nth-child(4) {
top: -1em;
}
.container p:nth-child(6) {
top: -2em;
}


/* Code below is just to animate the width for the sake of this example, and is not part of the solution */
@keyframes changewidth {
from { width: 100%; }
to { width: 1%; }
}

.container {
animation-duration: 5s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
<div class="container">
<div class="break"></div>
<p>Short summary</p>
<div class="break"></div>
<p>This is a shorter version of the summary text.</p>
<div class="break"></div>
<p>This is a really long version of the summary text. I could go on forever. Isn't this great?</p>
</div>

关于css - 文本开始溢出时如何使用动态替换文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38247323/

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