Search code examples
cssreactjsstyled-components

Nested styled component with nth-of-type


Recently play with styled components and trying to mix it with nth-of-type(1) but encountering a difficulty. From what I understand nth-of-type(1), it means to select the first related tag of its parent.

What I want to do is to select the first SectionWrapper in SPageWrapper but it doesn't take effect. There is no error.

Thank you very much in advance ! !

//page.js
import { PageWrapper } from "@pages/pageWrapper";

const Page = () => {
   return (
        <SPageWrapper>
            <DecoratedBackgroundImage/>
            <SectionWrapper>
                //first section wrapper
            </SectionWrapper>
            <SectionWrapper>
                 //second section wrapper
            </SectionWrapper>
        </SPageWrapper>
    );
}
//styled-component css

const SectionWrapper = styled.div`
    // other css
    align-items: center;
`;

const SPageWrapper = styled(PageWrapper)`
    ${SectionWrapper}:nth-of-type(1){
        align-items: flex-start;
    }
`;

Solution

  • This doesn't work because ${SectionWrapper} produces class name and not a tag in output styles (nth-of-type works with tags).

    One possible solution would be styling SectionWrapper with align-items: flex-start; and overriding adjacent siblings:

    const SPageWrapper = styled(PageWrapper)`
        ${SectionWrapper} {
            align-items: flex-start;
            
            & + & {
                align-items: stretch;
            }
        }
    `;