I have been learning react styled component and now I am stuck at a point where I am trying to style the first and last child of styled Wrapper in react and my styled are not applying.
Need help in understanding why it is not working.
Below is the codesandbox link and my code.
https://codesandbox.io/s/target-first-child-css-styled-components-forked-9i65re
import ReactDOM from "react-dom";
import styled from "styled-components";
const Text = styled.div`
color: green;
font-size: 20px;
&:first-child {
color: red;
}
&:last-child {
color: blue;
}
`;
function App() {
return (
<Text>
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
</Text>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodePudding user response:
this selectors means when the parent itself is the first child or the last child, in this case, it is both :D this is why it's blue, what you want to do is:
const Text = styled.div`
color: green;
font-size: 20px;
& div:first-child {
color: red;
}
& div:last-child {
color: blue;
}
`;
Which means when a child div
is the first or the last