React中媒体查询下display:none隐藏按钮失效问题求助
问题分析与解决方案
你的问题出在CSS选择器使用错误,导致隐藏规则完全没生效:
错误原因
你写的.nav-buttons:first-child是想匹配「作为父元素第一个子元素的.nav-buttons容器」,但看DOM结构:
<nav> <h2>showcasy.</h2> <div class="nav-buttons">...</div> <!-- 这是nav的第二个子元素 --> </nav>
.nav-buttons是<nav>的第二个子元素,第一个子元素是<h2>,所以这个选择器根本匹配不到任何元素,自然无法隐藏按钮。而且你的目标是隐藏.nav-buttons内部的第一个「Let's Talk」按钮,不是隐藏整个容器,选择器的层级逻辑完全搞反了。
修复方案
直接选中.nav-buttons内部的第一个按钮即可,修改媒体查询里的CSS:
@media (max-width: 767px) { /* 选中.nav-buttons下的第一个.custom-btn按钮 */ .nav-buttons > .custom-btn:first-child { display: none; } }
或者更简洁(因为.nav-buttons的直接子元素就是按钮):
@media (max-width: 767px) { .nav-buttons > :first-child { display: none; } }
额外优化建议
如果担心后续按钮结构变化选错元素,可以给「Let's Talk」按钮加专属类:
- 在Navbar.jsx里给第一个RoundedButton传入类名:
<RoundedButton text="Let's Talk" icon="return-up-forward-outline" invert={false} className="talk-button" />
- 在RoundedButton.jsx里合并传入的类名到按钮上:
<button style={whiteBorder && invert ? {border: "1px solid #fff"} : null} onClick={func != null ? func : null} className={`custom-btn ${invert ? "invert" : ""} ${className || ""}`} type="button">{text} {icon !== "" ? <ion-icon name={icon}></ion-icon> : null} </button>
- 最后CSS里直接隐藏这个类:
@media (max-width: 767px) { .talk-button { display: none; } }
内容的提问来源于stack exchange,提问作者BlackCult666
相关产品推荐
相关产品推荐

