Search code examples
javascriptreactjsstyled-components

How to style child components in react styled-components


I'm trying to style the child component of a styled-component, but it sends the css to the parent instead of the child/ This is my code,

export const Card = styled.div`
  position: relative;
  ${props => props.horizontal && `
  ${CardImage}{
     max-height: 60%;
     overflow: hidden;
  }`}
`
export const CardImage = styled.div`
    position: relative;
`

EDIT: When I add a condition before rendering that's when it doesn't work


Solution

  • You're almost there, you're just missing a $ in your code and you'll need to move the CardImage above the Card component:

    export const CardImage = styled.div`
        position: relative;
    `
    
    export const Card = styled.div`
        position: relative;
        ${CardImage}{
            max-height: 60%;
            overflow: hidden;
        }
    `
    

    Edit (04/04/2018):

    If you want to add a condition around a whole block like you have, you need to import the css function from styled components and use that:

    import styled, {css} from "styled-components";
    
    export const CardImage = styled.div`
        position: relative;
    `
    
    export const Card = styled.div`
        position: relative;
    
        ${props => props.horizontal && css` // - Notice the css` here.
            ${CardImage}{
                max-height: 60%;
                overflow: hidden;
            }
        `}
    `