【问题标题】:Maintain responsive image height保持响应式图像高度
【发布时间】: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


    【解决方案1】:

    正如您所提到的,从您的沙盒代码中看这个问题并不是很清楚。

    我不确定这是否能解决您的问题,但请尝试将您的 CTA 组件设置为具有 background-image() 而不是使用图像标签。

    确保也添加其他背景 css 属性,例如

    background-repeat: no-repeat;
    background-size: cover;
    background-posistion: center;
    padding-bottom: 60%;
    

    确保添加 padding-bottom: 60% (您的图像似乎有 3:2(w:h) 的比例);

    希望这对你有用!

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2016-01-09
      • 2015-03-23
      • 2014-03-01
      • 1970-01-01
      • 2015-08-21
      • 2014-04-14
      • 1970-01-01
      • 2014-03-01
      相关资源
      最近更新 更多