乐闻世界logo
搜索文章和话题

How to specify height fit content with tailwindcss

5 个月前提问
3 个月前修改
浏览次数151

5个答案

1
2
3
4
5

在Tailwind CSS中,要使元素的高度适应其内容,可以使用h-auto类,这相当于将CSS的height属性设置为auto,使得元素高度根据其内部内容自动调整。

例如,如果您有一个包含文本的div元素,想要它的高度根据内容来自动调整,那么可以这样写:

html
<div class="h-auto"> <!-- 这里是内容,div将根据内容自动调整高度 --> Lorem ipsum dolor sit amet, consectetur adipiscing elit... </div>

而如果你是想要在Flexbox布局中,让项目的高度根据内容来调整,可以使用items-start或类似的对齐类来确保flex项根据内容定高度。请注意,在这种情况下,高度的自适应是Flexbox属性的一部分,而不是通过TailwindCSS的高度工具类来直接控制。

以下是一个使用Flexbox的例子,其中flex项的高度会根据内容大小而自适应:

html
<div class="flex flex-col items-start"> <div class="..."> <!-- 这个项目会根据内容调整高度 --> Lorem ipsum dolor sit amet... </div> <div class="..."> <!-- 该项目的高度也会根据内容调整 --> Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua... </div> </div>

在实际应用中,你可能需要结合其他类来满足布局的需求,例如用于设置宽度、内边距、外边距或其他样式。 Tailwind CSS的设计原则就是提供细粒度的工具类来帮助你快速构建自定义的UI组件。

2024年6月29日 12:07 回复

Tailwind has now the class w-fit.

2024年6月29日 12:07 回复

Tailwind has now the class h-fit.

2024年6月29日 12:07 回复

you can create custom classes in your tailwind configuration for future use.

example:

shell
module.exports = { important: true, purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'], darkMode: 'class', // or 'media' or 'class' theme: { extend: { colors: { ... }, animation: { ... }, width: { ... }, margin: { ... }, height: { 76: '18rem', 78: '19rem', 82: '22rem', 97: '28rem', 98: '31rem', 99: '38rem', 100: '40rem', 'fit-content': 'fit-content(20em)', }, fontFamily: { mps: ['Clarkson', 'Helvetica', 'sans-serif'] }, flex: { 2: '1 1 25%', 3: '1 1 30%', 4: '1 1 40%', 5: '1 1 50%', 6: '1 1 60%', } }, }, variants: { extend: {}, }, plugins: [], }
2024年6月29日 12:07 回复

I managed to fix my issue by setting h-full in both <textarea> and setting flex-none in my problematic <div>, resulting in the following code:

shell
<form className="w-full flex h-96 gap-2 mt-8 flex-wrap"> <textarea role="text-input" className="h-full resize-none flex-1" placeholder="INPUT" /> <textarea role="text-output" className="h-full resize-none flex-1" placeholder="OUTPUT" readOnly /> <div className="w-full flex flex-none"> // This is the troublesome div <button> Submit! </button> </div> </form>
2024年6月29日 12:07 回复

你的答案