我有一个样式组件如下
const StyledCustomComponent = styled.aside`
min-width: ${gridPts(19)};
background-color: ${HIGHLIGHT_BLUE};
flex: 0 0 auto;
${fontSize(13)}
padding: ${gridPts(2)};
@media only screen and (max-width: ${MQ_320}) {
padding: ${gridPts(1)};
}
@media only screen and (min-width: ${MQ_1285}), (min-width: ${MQ_575}) and (max-width: ${MQ_961}) {
&:first-child {
margin-top: 0;
}
}
`
当我在浏览器中检查它并调整大小以匹配媒体查询时,:first-child样式不适用。
以上组件的子组件的样式如下
const StyledCustomComponentChild = css`
margin: ${gridPts(1)} ${gridPts(1)} 0;
@media only screen and (max-width: ${MQ_575}), (min-width: ${MQ_961}) and (max-width: ${MQ_1285}) {
display: inline-block;
float: left;
margin-right: ${gridPts(1)};
& * {
display: inline-block;
margin-right: ${gridPts(1)};
}
}
@media only screen and (min-width: ${MQ_1285}), (min-width: ${MQ_575}) and (max-width: ${MQ_961}) {
display: block;
line-height: 1.5em;
margin: ${gridPts(3)} 0;
white-space: nowrap;
&:first-child {
display: block;
}
}
`
此样式应用于组件本身而不是其第一个子项
这是在浏览器开发工具中如何解释样式的屏幕截图
请注意space
之前没有:first-child
如果我通过开发工具手动添加空格,则按预期应用样式
import styled from 'react-emotion'
const StyledDiv = styled.div`
color: turquoise;
& :last-child {
color:green;
}
& :first-child {
color: red;
}
`
render(
<StyledDiv>
<p>First</p>
<p>Second</p>
<p>third</p>
<p>last</p>
</StyledDiv>
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
有人可以猜出可能是什么问题吗?
答案 0 :(得分:1)
两个选择器都对我有用。在:last-child之前使用<div/>
或<p/>
等标签,(取决于您的代码,它也可能是另一个标签)。
export const blogSection = css`
disaply:flex
& div:last-child {
background: #ff0000;
}
`;