如何基于子输入框placeholder状态修改Tailwind容器边框
问题
希望子输入框的placeholder不再显示时,修改其父容器的边框颜色。此前用focus-within实现了近似效果,但不理想——需要边框在失去焦点后仍根据输入框是否有文本保持着色状态。
想实现类似代码中label的效果,但不想使用peer,而是基于子元素的状态来实现。
目前尝试的has-[:not(:placeholder-shown)]:border-blue-500并未生效:蓝色边框一开始就处于激活状态,而它应该仅在输入文本(placeholder消失)时才激活。
要求无需JavaScript实现该效果。
原始代码示例:
<html> <head> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="m-4"> <!--Name input--> <div class="group relative border-gray-900 border flex px-[16px] py-[8px] h-[54px] items-center has-[:not(:placeholder-shown)]:border-blue-500"> <input id="name" type="text" placeholder="Name" class="peer placeholder:text-gray-500 placeholder:text-base block outline-none" /> <label for="name" class="absolute left-[16px] -top-2.5 bg-white px-1 text-sm text-gray-600 transition-all duration-300 peer-placeholder-shown:opacity-0 peer-placeholder-shown:top-[16px] peer-[:not(:placeholder-shown)]:opacity-100 peer-[:not(:placeholder-shown)]:-top-2.5"> Name </label> </div> </body> </html>
解决方案
问题出在has选择器的范围没有限定:你当前的has-[:not(:placeholder-shown)]会匹配父容器内所有满足条件的子元素,而label元素本身没有placeholder属性,所以:not(:placeholder-shown)对它来说始终为真,导致父容器一开始就触发了蓝色边框样式。
只需要给has选择器明确指定目标为input元素即可,修改父容器的class中对应的规则:
<html> <head> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="m-4"> <!--Name input--> <div class="group relative border-gray-900 border flex px-[16px] py-[8px] h-[54px] items-center has(input:not(:placeholder-shown)):border-blue-500"> <input id="name" type="text" placeholder="Name" class="peer placeholder:text-gray-500 placeholder:text-base block outline-none" /> <label for="name" class="absolute left-[16px] -top-2.5 bg-white px-1 text-sm text-gray-600 transition-all duration-300 peer-placeholder-shown:opacity-0 peer-placeholder-shown:top-[16px] peer-[:not(:placeholder-shown)]:opacity-100 peer-[:not(:placeholder-shown)]:-top-2.5"> Name </label> </div> </body> </html>
说明
has(input:not(:placeholder-shown))会精准检测父容器内的input元素是否处于placeholder未显示的状态(即输入框有内容)- 只有当
input满足条件时,父容器才会应用border-blue-500样式,初始状态下输入框为空,placeholder显示,边框保持默认的border-gray-900 - 完全不需要JavaScript,纯CSS(Tailwind)实现需求
内容的提问来源于stack exchange,提问作者Linards Liepenieks
相关产品推荐
相关产品推荐

