为何为父容器内除最后一个外的StyledDiv设置样式未生效?
问题根源
你写的&:last-child选择器只在当前StyledDiv是其父容器的最后一个子元素时才生效,但你的父容器最后一个子元素是那个普通<div>,第二个StyledDiv根本不是父容器的最后一个子元素,所以它的底部外边距没被去掉。
解决办法
推荐用相邻兄弟选择器来实现,这种方式不受父容器内其他非StyledDiv元素的影响,兼容性和灵活性更强:
const StyledDiv = styled.div` width: 100%; display: flex; flex-direction: column; // 只有当前StyledDiv后面紧跟着另一个StyledDiv时,才添加上边距 & + & { margin-top: 24px; } `; // 原有结构无需改动 <div> <StyledDiv className='childDiv'> <p>Hello World 1</p> </StyledDiv> <StyledDiv className='childDiv'> <p>Hello World 2</p> </StyledDiv> <div> <p>Some other text and not a styled div</p> </div> </div>
如果一定要保留margin-bottom的写法,可以给父容器创建一个Styled组件,精准控制子元素样式:
const ParentContainer = styled.div` // 选中所有子StyledDiv,排除最后一个 ${StyledDiv}:not(:last-of-type) { margin-bottom: 24px; } `; // 将原有父div替换为该组件 <ParentContainer> <StyledDiv className='childDiv'> <p>Hello World 1</p> </StyledDiv> <StyledDiv className='childDiv'> <p>Hello World 2</p> </StyledDiv> <div> <p>Some other text and not a styled div</p> </div> </ParentContainer>
注:第二种方法里last-of-type能生效是因为StyledDiv和普通div都是<div>标签,若父容器内还有其他类型的Styled组件,可能需要调整选择器。
内容的提问来源于stack exchange,提问作者Cookies
相关产品推荐
相关产品推荐

