【问题标题】:Nested component is overriding the style of parent component?嵌套组件是否覆盖了父组件的样式?
【发布时间】:2020-02-21 20:33:13
【问题描述】:

我正在尝试在彩色背景中放置一个大白框,但我遇到了问题 我的嵌套组件似乎正在对其父组件应用边距,而不仅仅是在其自身上。这是两个组件的代码:

Background.js:

const Background = styled.div`
    background: linear-gradient(
      to bottom right,
      ${props => props.theme.color_primary_light},
      ${props => props.theme.color_primary_dark});
    background-size: cover;
    background-repeat: no-repeat;
    /* text color for all children */
    color: ${props => props.theme.color_grey_dark_2};
    min-height: 100vh;
`;

Container.js:

const Container = styled.div`
  max-width: 120rem;
  background-color: ${props => props.theme.color_grey_light_1};
  box-shadow: ${props => props.theme.shadow_dark};
  min-height: 50rem;

  /*This margin seems to be applied to the parent*/
  margin: 8rem auto;
`;

这就是我在 App.js 主组件中调用它们的方式:

const App = () => {
  return (
    <ThemeProvider theme={theme}>
      <Background>
        <Container>
        </Container>
      </Background>
    </ThemeProvider>
  );
}

现在这就是我想要达到的效果。但是,我只能通过使用纯 HTML 和 CSS 来重新创建它,并且它可以按预期工作。 Background 和 Container 都是 div,Container 是 Background 的直接子代。我应用的 CSS 与上面列出的样式组件完全相同。

但是,我在 styled-components 示例中实际得到的是以下内容:

这有点难以分辨,但顶部应用了 8rem 边距,这实际上是 同时将 Background 和 Container 组件向下推,而不是在 Background 内将 Container 向下移动 8rem。

我想知道是否有人知道为什么会这样,以及我应该注意什么来解决这个问题。在过去的一个月里,我只是在练习 CSS,所以这可能是一个我似乎忽略的明显修复,但我就是想不通。

【问题讨论】:

    标签: css styled-components


    【解决方案1】:

    嗯,我想通了。在 Container.js 中,我的意思是设置 min-width 属性,而不是“max-width”。这些简单的错误可能非常烦人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 2019-04-15
      • 2019-10-02
      • 2019-04-23
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多