Search code examples
styled-components

Sibling component styling with styled-components


This is quite a simple case which I can't, for some reason, get to work. I have a styled-components Container, and I'd like to define the styles of p inside that container like so:

const Container = styled.div`
  & p {
    margin: 0;
    & + & {
      margin-top: 10px;
    }
  }
`

So, I would expect whenever there's more that on p inside the Container, that the second p would get a top-margin, but this doesn't happen.

Here's a codesandbox.

Any ideas?


Solution

  • I just inverted the condition. Is this want you want?

    CodeSandbox

    import styled from "styled-components";
    
    const Container = styled.div`
      background: grey;
      & p:nth-child(1) {
        margin: 0px;
      }
      & p {
        margin-top: 10px;
      }
    `;
    
    export default function App() {
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          <Container>
            <p>Line One</p>
            <p>Line Two</p>
            <p>Line Two</p>
          </Container>
        </div>
      );
    }