EN VI

Reactjs css styled components - target first-child and last-child not working

2022-05-29 15:59:06

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.

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);

Solution:

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 chil div is the first or the last

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login