使用Tailwind CSS flex-1属性如何为整个元素而非仅文本设置背景色
你目前的悬浮背景只覆盖部分区域,是两个结构和样式层级的问题导致的:
hover:bg-red-500加在了内层div上,而你每个标签项最外层的flex-1div设置了px-1左右内边距,这部分区域不属于内层div,自然不会被悬浮背景覆盖- 内层div没有设置上下内边距,高度仅由内容和span的上下外边距撑开,不会填充满整个标签栏的高度
直接把交互相关的样式、布局属性都移到最外层的flex-1标签容器上即可,调整后的标签部分代码如下:
<template> <!-- CONTAINER --> <div class="flex-col bg-gray-200 w-11/12 rounded-xl border-2 m-auto pt-2 mt-2" > <!-- MAIN CONTENT --> <div class="flex pb-2 bg-green-500 py-10">MAIN CONTENT</div> <!-- Tabs --> <div class="flex w-full text-sm text-center items-center bg-blue-500"> <!-- 调整后的单个标签结构,hover、布局属性都在外层容器 --> <div class="flex-1 px-1 hover:bg-red-500 cursor-pointer flex justify-center py-4"> <span>Tab 1</span> </div> <div class="flex-1 px-1 hover:bg-red-500 cursor-pointer flex justify-center py-4"> <span>short tab 2</span> </div> <div class="flex-1 px-1 hover:bg-red-500 cursor-pointer flex justify-center py-4"> <span>Long Tab name 3</span> </div> <div class="flex-1 px-1 hover:bg-red-500 cursor-pointer flex justify-center py-4"> <span>This is super Long Tab name 4</span> </div> <div class="flex-1 px-1 hover:bg-red-500 cursor-pointer flex justify-center py-4"> <span>This is SUPER extra long tab name 5</span> </div> </div> </div> </template>
如果需要实现选中永久高亮,直接给当前选中的标签外层容器加一个固定背景色的类即可,比如bg-yellow-500,Tailwind中类的优先级足够覆盖悬浮样式,不需要额外调整。
内容的提问来源于stack exchange,提问作者babis95
相关产品推荐
相关产品推荐

