【发布时间】:2021-04-27 05:33:16
【问题描述】:
我正在尝试在我的 react 应用程序顶部创建一个 CTA 组件,其中包含导航栏和 CTA 文本。成功完成组件后,我注意到我想要解决的一个小错误。我只提供宽度为 100% 且没有定义高度的图像。这会导致图像下方的 div 向上闪烁,直到图像完全加载。我知道没有提供具有定义高度的图像会导致它,因为当我提供具有随机高度的图像时,错误就会消失。我想知道是否有一种方法可以为图像提供响应高度,其行为方式类似于仅提供 100% 宽度的图像。
我的css代码如下:
body {
margin: 0;
padding: 0;
}
.container {
position: relative;
}
.container .container-background {
opacity: 0.25;
}
.container-background-img {
width: 100%;
position: relative;
}
.container .content {
position: relative;
z-index: 1;
}
.app-outer {
max-width: 1170px;
margin: 0 auto;
position: relative;
padding: 0rem 1rem;
}
@media only screen and (max-width: 1170px) {
.container-background-img {
height: 656px;
object-fit: cover;
}
}
@media only screen and (max-width: 768px) {
.container-background-img {
height: 653px;
object-fit: cover;
}
}
/* CODE ADDED */
#navbar {
position: absolute;
top: 0;
left: 0;
right: 0;
}
#content {
position: absolute;
top: 20%;
}
我的jsx代码如下:
import React from "react";
import "./styles.css";
export default function App() {
return (
<>
<div className="container">
<div className="container-background">
<img
id="rob"
src="https://i.imgur.com/iyFtMNA.jpg"
alt="bg"
className="container-background-img"
/>
</div>
<div id="content" className="content">
I am the CTA
</div>
<div id="navbar">
<div
style={{
backgroundColor: "white",
height: 100,
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
I am the navbar
</div>
</div>
</div>
<div>I am beneath the cta</div>
</>
);
}
我提供的以下链接包含一个代码沙箱:https://codesandbox.io/s/issue-react-forked-4lsdm?file=/src/App.js:0-868
请注意:*** 在代码沙箱中问题不是很明显,但在我的反应应用程序中更明显
【问题讨论】:
标签: javascript css reactjs sass