React+Tailwind视口类适配问题:移动端需始终显示Hover效果
解决方案
方法一:纯Tailwind实现(推荐)
直接利用Tailwind的断点+伪类组合,无需额外自定义CSS类,代码更简洁:
import { features } from "../constants"; import styles from "../style"; const FeatureCard = ({ icon, title, content, index }) => ( <div className={` flex flex-row p-6 rounded-[20px] max-md:bg-[var(--black-gradient)] max-md:shadow-[var(--card-shadow)] md:hover:bg-[var(--black-gradient)] md:hover:shadow-[var(--card-shadow)] ${index !== features.length - 1 ? "mb-6" : "mb-0"} `}> <div className={` w-[64px] h-[64px] rounded-full ${styles.flexCenter} bg-dimBlue` }> <img src={icon} alt="star" className=" w-[50%] h-[50%] object-contain" /> </div> <div className="flex-1 flex flex-col ml-3"> <h4 className=" font-poppins font-semibold text-white text-[18px] leading-[23.4px] mb-1"> {title} </h4> <p className=" font-poppins font-normal text-dimWhite text-[16px] leading-[24px] "> {content} </p> </div> ); export default FeatureCard;
逻辑说明:
max-md:xxx:视口宽度小于768px时,卡片始终显示背景渐变和阴影md:hover:xxx:视口宽度≥768px时,仅hover状态下才显示背景渐变和阴影
方法二:结合自定义CSS类实现
如果你习惯用自定义类区分状态,调整类的断点前缀即可:
修改后的JSX:
import { features } from "../constants"; import styles from "../style"; const FeatureCard = ({ icon, title, content, index }) => ( <div className={` flex flex-row p-6 rounded-[20px] max-md:feature-card-small md:feature-card ${index !== features.length - 1 ? "mb-6" : "mb-0"} `}> <div className={` w-[64px] h-[64px] rounded-full ${styles.flexCenter} bg-dimBlue` }> <img src={icon} alt="star" className=" w-[50%] h-[50%] object-contain" /> </div> <div className="flex-1 flex flex-col ml-3"> <h4 className=" font-poppins font-semibold text-white text-[18px] leading-[23.4px] mb-1"> {title} </h4> <p className=" font-poppins font-normal text-dimWhite text-[16px] leading-[24px] "> {content} </p> </div> ); export default FeatureCard;
保留你的CSS:
.feature-card:hover { background: var(--black-gradient); box-shadow: var(--card-shadow); } .feature-card-small { background: var(--black-gradient); box-shadow: var(--card-shadow); }
逻辑说明:
max-md:feature-card-small:仅在视口<768px时加载该类,让卡片始终显示hover状态样式md:feature-card:仅在视口≥768px时加载该类,通过:hover伪类触发样式
原代码失效原因
你之前的写法存在两个问题:
- 断点前缀错误:使用了不存在的
ss断点,且max-sm默认对应<640px的屏幕,不符合你需要的<768px范围 - 类名前缀叠加错误:正确的断点前缀应该直接加在类名前(如
max-md:feature-card-small),而非多层前缀嵌套
可选:验证Tailwind断点配置
如果不确定断点对应的像素值,可检查tailwind.config.js中的配置,确保md对应768px:
module.exports = { theme: { screens: { 'sm': '640px', 'md': '768px', 'lg': '1024px', // 其他断点配置 }, }, }
内容的提问来源于stack exchange,提问作者protoys
相关产品推荐
相关产品推荐

