如何使用Styled Components在小屏设备上隐藏按钮?
Hey there! I totally get why this is frustrating—let's break down why your media query isn't kicking in and fix it properly.
The Root Cause: Priority Conflicts
Your base styles use multiple !important declarations, which cranks up their priority way higher than the media query's display: none (which doesn't have !important). Even though Styled Components generates unique class names, !important overrides normal specificity rules, so your small-screen style gets ignored entirely.
Solution 1: Add !important to the Media Query Style (Quick Fix)
If you just need a fast, immediate fix, you can add !important to the display: none in your media query to match the priority of your base styles:
export const BigScreenButton = styled(Button)` color: white !important; border: 2px solid white !important; border-radius: 3px !important; padding: 0 10px; margin-left: 10px !important; @media screen and (max-width: 700px) { display: none !important; } `;
Solution 2: Ditch !important (Better Long-Term Fix)
!important makes style debugging a headache down the line, so a cleaner approach is to use Styled Components' built-in specificity boost with && instead. This doubles up the generated class name, making your styles override the inherited Button's styles without needing !important:
export const BigScreenButton = styled(Button)` && { color: white; border: 2px solid white; border-radius: 3px; padding: 0 10px; margin-left: 10px; } @media screen and (max-width: 700px) { && { display: none; } } `;
Quick Sanity Check
Just to be thorough, your media query syntax is perfect—@media screen and (max-width: 700px) is exactly the right way to target screens 700px and smaller. The main issue here is definitely the specificity conflict from those !important tags.
Give either solution a try, and your button should disappear on small screens like expected!
内容的提问来源于stack exchange,提问作者James

