React-当父组件收缩时,使子组件收缩

时间:2018-12-24 00:49:15

标签: css reactjs sass

我有一些简单的东西。

我有一个Banner组件,其外观如下

const banner = (props: IBannerProps) => {
  // ...
  return (
    <div className={classes.Banner}>
      {props.children}
    </div>
  );
};

还有卡片组件

const card = (props: ICardProps) => {
    return <div className={classes.Card}>{props.children}</div>;
};

我想按如下方式使用它们

const home = () => (
    <>
        <Banner backgroundImage="home">
            <Card> Quack </Card>
        </Banner>
    </>
);

现在,我的想法是我希望卡片随着横幅的尺寸缩小而缩小。

现在,我的横幅CSS如下

.Banner {
    background-image: // some image
    height: 60vh;
    width: 100vw;
    background-position: center -280px;
    background-repeat: no-repeat;
    background-size: cover;
}

我的卡是

.card {
    border: 2px solid green;
    height: 80%;
    width: 80%;
}

发生了什么事,当我缩小页面时,我的卡高度大于横幅高度->看图片

enter image description here

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么您应该能够通过对CSS进行以下更改来解决您的问题:

.Banner {
    background-image: // some image
    height: 60vh;
    width: 100vw;
    background-position: center; // remove -280px
    background-repeat: no-repeat;
    background-size: cover;

    // Add this to allow absolute position of child card
    position:relative;
}

.card {
    border: 2px solid green;
    height: 80%;
    width: 80%;
}

// When a card exists in banner, position it with absolute
// and force the boundary of the card to match the boundary
// of the banner
.Banner .card { 
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
}