Tailwind CSS中attr结合content伪元素失效,如何添加长段落?
解决方法
要实现鼠标悬停时显示长文本段落,你需要把JS变量绑定到元素的自定义HTML属性上,再通过Tailwind的伪元素读取该属性,同时处理文本换行和布局问题。以下是修正后的代码:
const myText = "This is a Paragraph for Testing css Tailwind. You can add multiple lines here, and it will wrap properly when hovered. No need to use underscores to concatenate text anymore."; <div className="bg-blue-700 text-white p-4 relative cursor-pointer hover:after:opacity-100 after:opacity-0 after:absolute after:top-full after:left-0 after:mt-2 after:bg-gray-800 after:text-white after:p-3 after:max-w-md after:white-space-pre-wrap after:rounded-md after:transition-opacity after:duration-300 after:content-[attr(data-tooltip)]" data-tooltip={myText} > Hover Me </div>
关键说明:
- 绑定自定义属性:通过
data-tooltip={myText}将JS变量值赋值给元素的data-tooltip属性,这样CSS可以读取完整长文本,无需用下划线拼接。 - 伪元素显示控制:用
after伪元素承载提示文本,通过opacity切换显示状态(比display: none过渡更平滑),搭配transition-opacity实现淡入淡出效果。 - 文本布局优化:
white-space-pre-wrap确保文本自动换行,max-w-md限制提示框宽度避免过宽,absolute定位让提示框脱离文档流,不干扰原有页面布局。 - Tailwind核心语法:
after:content-[attr(data-tooltip)]是实现文本读取的关键,它会从元素的data-tooltip属性中获取内容作为伪元素的文本。
内容的提问来源于stack exchange,提问作者Mostafa Hosseini
相关产品推荐
相关产品推荐

