I'm trying to replicate some CSS in Emotion using Partials but I don't see how it's possible to replicate a rule like :first-of-type
in a situation where I'm using a partial
. Is there some way to achieve this?
Starting CSS:
li.item {
background: white;
border: 1px solid;
}
li.item.isResult:first-of-type {
background: pink; /* Don't know how to port this rule */
}
Best attempt at porting this rule to Emotion:
import styled from '@emotion/styled';
import { css } from '@emotion/core';
const Item = styled.li`
background: white;
border: 1px solid;
${resultPartial}
`
const resultPartial = props => props.isResult && css`
&:first-of-type {
background: pink; // Has no effect
}
`
PS: Although partial
s don't seem to be mentioned in Emotion's docs, they are supported and do work. I'm specifically wondering about how to go about recreating a :first-of-type
rule inside a partial.
Not a solution, but an explanation why it doesn't work.
const Div = styled.div`
color: black;
&:first-of-type {
color: red;
}
`;
Generates CSS like this:
.HaSh{color: black}
.HaSh:first-of-type{color: red}
However, the CSS spec only allows "type" to be a tag name for first/nth/last/only-of-type
. Yet, styled-components
relies and must rely on class names to distinguish differently styled div
's. Thus, a dead end.
I believe you can work around the limitation (in general) by setting the style on any "parent's child", eg:
const Comp = () => <Container><p>1</p><p>2</p></Container>;
const Container = styled.div`
& > *:first-of-type {
color: red;
}
`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.