将含嵌套类的CSS转换为Styled Components的问题咨询
Hey there! No worries at all—nested styles in styled-components are actually really straightforward once you get the hang of them, and they map pretty closely to your original CSS structure. Let's break this down step by step to match your existing code.
Full Styled Components Implementation
First, here's the complete code that replicates your original CSS and HTML structure:
import styled from 'styled-components'; const CFContainer = styled.div` position: relative; height: 281px; width: 450px; margin: 0 auto; /* Target all img children inside the container */ & img { position: absolute; left: 0; -webkit-transition: opacity 1s ease-in-out; -moz-transition: opacity 1s ease-in-out; -o-transition: opacity 1s ease-in-out; transition: opacity 1s ease-in-out; /* Target the img with .top class on hover */ &.top:hover { opacity: 0; } } `; // Then use it in your JSX function ImageFader() { return ( <CFContainer> <img className="bottom" src="/images/Cirques.jpg" /> <img className="top" src="/images/Clown%20Fish.jpg" /> </CFContainer> ); } export default ImageFader;
Let's Break Down the Nested Logic
Let's map this directly to your original CSS to make it clear:
- The
CFContainercomponent replaces your#cfdiv—all the top-level styles here match exactly what you had for#cf. - The
& imginsideCFContaineris equivalent to your original#cf imgselector. The&in styled-components refers to the parent selector (in this case,CFContainer), so this targets all<img>elements inside the container. - The nested
&.top:hoverinside the& imgblock corresponds to your#cf img.top:hoverselector. Here,&now refers to the parent of this block (which is& img), so it translates toimg.top:hoverwithin the container.
This nested structure mirrors your original CSS hierarchy perfectly, so you don't have to break up styles into separate components unless you want to. It's one of the nice things about styled-components—it lets you keep related styles grouped together just like you would in vanilla CSS.
内容的提问来源于stack exchange,提问作者Filip Strelec

