Search code examples
javascriptcssreactjsecmascript-6styled-components

how to use sibling selector css in styled


I have a styled component which looks like:

import styled from 'styled-components';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';

export const CategoryList = styled(List)`
`;
//this is what i want to change
export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;
`;

export const CategoryListItemText = styled(ListItemText)`
  padding-left: 5px;
`;

export const ListItemHeading = styled(ListItem)`
  background-color: #f4f4f4;
`;

How can I use siblings in this case & + & ?

I want to achieve something like :

li + li {
border-top: 1px solid red;
}

How can I achieve this?


Solution

  • This is done the same way as in SCSS with &:

    export const CategoryListItem = styled(ListItem)`
      border-top: 2px solid #f4f4f4;
    
      & + & { // this will work for <CategoryListItem /><CategoryListItem />
        border-top: 1px solid red;
      }
    `;
    

    You can also style with html elements but the code above is a better practice

    & + li { // this will work for <CategoryListItem /><li />
      border-top: 1px solid red;
    }
    

    Basically you can do any nesting with &

    & li { // this will work for <CategoryListItem><li /></CategoryListItem>
    }
    & li.test { // this will work for <CategoryListItem><li class="test" /></CategoryListItem>
    }
    

    You can read it up in the official docs: https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting