使用Tailwind CSS的自动增长文本区域

A preview of the form that contains the auto-expandable textarea

I really enjoy building user interfaces with CSS, it lets me do almost anything I want. However, at times, it can be frustrating when common functionalities are not natively supported. For example, there’s currently no built-in feature in CSS that allows me to adjust the height of a textarea based on its content. There is ongoing discussion about introducing a field-sizing property in CSS, but it is still in the early stages.

我非常喜欢使用CSS构建用户界面,它让我几乎可以做任何我想做的事情。然而,有时候,当常见的功能不被原生支持时,这可能会让人沮丧。例如,目前CSS中没有内置的功能可以根据内容调整textarea的高度。关于引入CSS的field-sizing属性的讨论正在进行中,但它仍处于早期阶段。

So, if you want a textarea that gets taller as more text is added, you have to use JavaScript or a simple CSS trick like the one I’m about to show you.

因此,如果你想要一个随着添加更多文本而变高的textarea,你必须使用JavaScript或者像我即将展示的简单的CSS技巧

The idea comes from Stephen Shaw, and it’s very simple: you nest the textarea within another element configured as a grid. Then, you add a pseudo-element inside it replicating the textarea content. This pseudo-element will expand to fit the content, which in turn makes the outer grid element (and therefore the textarea) expand to the same height. So, as you add more text, the textarea grows to fit it.

这个想法来自Stephen Shaw,非常简单:你将textarea嵌套在另一个配置为网格的元素中。然后,在其中添加一个伪元素来复制textarea的内容。这个伪元素会根据内容自动扩展,从而使外部网格元素(以及textarea)的高度也会相应扩展。因此,随着添加更多文本,textarea会自动调整高度。

We’ve reproduced this trick with Tailwind CSS. To use it, take the outer div and wrap your textarea with it. Ensure that your textarea includes the onInput event – it’s responsible for updating the content of the pseudo-element. Lastly, check that the padding of the textarea and the pseudo-elements are the same, and you’re good to go!

我们使用Tailwind CSS复现了这个技巧。要使用它,将外部的div包裹在你的textarea周围。确保你的textarea包含onInput事件 - 它负责更新伪元素的内容。最后,检查textarea和伪元素的padding是否相同,然后你就可以开始使用了!

Code

代码

<div class=" grid text-sm after:px-3.5 after:py-2.5 [&>textarea]:text-inherit after:text-inherit [&>textarea]:resize-none [&>textarea]:overflow-hidden [&>textarea]:[grid-area:1/1/2/2] after:[grid-area:1/1/2/2] after:whitespa...
开通本站会员,查看完整译文。

trang chủ - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.3. UTC+08:00, 2024-11-28 19:05
浙ICP备14020137号-1 $bản đồ khách truy cập$