【问题标题】:Maintain background image responsiveness regardless of screen size无论屏幕大小如何,都能保持背景图像响应能力
【发布时间】:2021-04-20 19:55:52
【问题描述】:

我目前正在使用 CRA 开发单页应用程序。我正在尝试创建一个位于应用程序顶部并包含叠加层的英雄图像。对于英雄图像,我使用的是背景图像。我遇到的问题是保持背景图像的整体响应能力。无论屏幕大小如何,我都希望用户能够看到整个背景图像。

以下链接显示了我试图达到的效果:https://www.youtube.com/watch?v=gfzWLbAbcCw&feature=youtu.be

我的 JSX 代码如下:

import React from "react";
import "./styles.scss";

export default function App() {
  return (
    <>
      <div className="container">
        <div className="container-background"> </div>
        <div className="content">
          <div style={{ textAlign: "center", paddingTop: 20 }}>Welcome</div>
        </div>
      </div>
    </>
  );
}

我的CSS代码如下:

body {
  margin: 0;
  padding: 0;
}

.container {
  position: relative;
}
.container .container-background {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url('https://i.imgur.com/iyFtMNA.jpg');
  opacity: .2;
  height: 1200px;
}
.container .content {
  position: relative;
  z-index: 1;
}

对于我可以利用哪些 css 属性来实现我想要的效果,我遇到了很多困难。欢迎提出任何建议!

以下链接https://codesandbox.io/s/vigilant-wozniak-t8wmx?file=/src/styles.scss:0-391 包含用于调试的沙箱

【问题讨论】:

    标签: css reactjs sass


    【解决方案1】:

    +1 用于代码盒沙盒 我会这样实现

    反应

       <div className="container">
          <div className="hero">
            <img src="https://i.imgur.com/iyFtMNA.jpg" alt="bg" />
            <div className="overlay">
              <h1 className="title">Title</h1>
              <h2 className="subtitle">Subtitle</h2>
            </div>
          </div>
          <div className="content">
            <div style={{ textAlign: "center", paddingTop: 20 }}>Welcome</div>
          </div>
        </div>
    

    css

    * { margin: 0; padding: 0; }
    .hero {
      position: relative;
    }
    .hero img {
      width: 100%;
      opacity: .2;
    }
    .hero .overlay {
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%, -50%);
    }
    .container .content {
      position: relative;
    }
    

    bg-overlay-example

    【讨论】:

    • @RobertTerrell 它回答了你的问题吗?
    【解决方案2】:

    为此,您需要为响应版本设置不同的图像,或者您可以使用background-size: 100% auto; 来查看整个图像,但您需要降低该div 的高度

    【讨论】:

    • 减少?你的意思是 div 的整体高度吗?随着屏幕变小,使用不同大小的图像
    • 100% auto 似乎可行,现在我遇到的唯一问题是我无法再通过更改 div 高度来控制图像的整体高度
    • 你能不能分叉我的代码沙箱并给我一个例子来说明你将如何处理这个
    • 否则您可以根据常用分辨率在编辑器中更改图像大小,这对您来说应该更容易。然后为响应式,您可以使用@media 查询设置响应式
    • 如果可能的话,你能通过我附加的代码沙箱链接告诉我吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多