pet*_*gan 13 css sass reactjs styled-components
我正在使用样式组件并希望定位 的第一个孩子Text
,但我无法这样做。
const Text = styled.p`
font-size: 12px;
&:first-child {
margin-bottom: 20px;
}
`;
... component
return(
<div>
<p>I am just regular text</p>
<p>Me too</p>
<Text>Hello Joe</Text> // this should have the margin bottom
<Text>Goodbye</Text >
</div>
)
Run Code Online (Sandbox Code Playgroud)
Thi*_*ker 22
最后,我得到了你的问题。样式组件与前两个本机p
标记(从我的角度来看)混淆,这就是未应用 CSS 的原因。
我将使用这样的解决方法:
const Text = styled.p`
font-size: 12px;
color: blue;
&:nth-child(3) {
margin-bottom: 20px;
color: red !important;
}
`;
Run Code Online (Sandbox Code Playgroud)
通过这样做,您p
为 CSS选择了第三个孩子(包括前两个标签)
或者,您可以执行以下操作:为标签添加类名并为该类提供 CSS。
const Text = styled.p`
font-size: 12px;
color: blue;
&.colors {
margin-bottom: 20px;
color: red !important;
}
`;
<div>
<p>I am just regular text</p>
<p>Me too</p>
<Text className="colors">Hello Joe</Text>
<Text>Goodbye</Text>
</div>
Run Code Online (Sandbox Code Playgroud)
这是演示
希望能帮助到你 :)
&
和之间不应该有空格:first-child
&:first-child {
margin-bottom: 20px;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
像这样使用
const Text = styled.p`
font-size: 12px;
> * {
&:first-child {
margin-bottom: 20px;
}
}
`;
Run Code Online (Sandbox Code Playgroud)