Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  191] [ 3]  / answers: 1 / hits: 30338  / 6 Years ago, mon, april 2, 2018, 12:00:00

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


More From » reactjs

 Answers
325

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;
}
`}
`

[#54789] Friday, March 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnaj

Total Points: 490
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;