:first-child 选择器不适用于情感 CSS

Rah*_*dav 6 css css-selectors reactjs

我有一个如下样式的组件

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;
  }
}
`
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中检查它并调整大小以匹配媒体查询时,: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;
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

此样式应用于组件本身而不是其第一个子组件

这是浏览器开发工具中如何解释样式的屏幕截图

在此输入图像描述

space请注意,之前没有:first-child 如果我通过开发工具手动添加空格,则样式将按预期应用

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;
  }
}
`
Run Code Online (Sandbox Code Playgroud)
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;
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

谁能猜出可能是什么问题吗?

小智 3

两个选择器都适合我。<div/>在 :last-child 之前使用类似或等的标签<p/>(根据您的代码,它也可能是另一个标签)。

export const blogSection = css`
  display:flex;
  & div:last-child {
  background: #ff0000;
  }
`;
Run Code Online (Sandbox Code Playgroud)