【问题标题】:Setting background image to full screen React将背景图像设置为全屏 React
【发布时间】:2021-09-12 08:19:17
【问题描述】:

我正在尝试将背景图像设置为全屏。

App.js:

import React from 'react';
import backgroundImage from './Resources/img.jpeg'

function App() {
  return (
    <div className="container"
    style={{ backgroundImage: `url(${backgroundImage})` }}  >
      <h1>Hello</h1>
    </div>
  );
}

export default App;

index.css

.container {
  height: 100%;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
}

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>Weakly Scheduler</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

图像被剪切,仅显示 Hello 所在的部分。如果我添加更多这些图像,则图像“显示”更多它的高度。由此我认为容器本身不是全屏的,但我不知道为什么。宽度是我想要的全屏。和想法?

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    index.css

    body, html {
        height: 100%;
        margin: 0;
        padding:0;
    }
    
    .container {
            width: '100vw';
            height: '100vh';
            background-image: `url(${backgroundImage})`;
            background-position: 'center';
            background-size: 'cover';
            background-repeat: 'no-repeat';
    }
    

    或者,

    const containerStyle= {
            width: '100vw',
            height: '100vh',
            backgroundImage: `url(${backgroundImage})`,
            backgroundPosition: 'center',
            backgroundSize: 'cover',
            backgroundRepeat: 'no-repeat',
    }
    
    function App() {
      return (
        <div className="container"
          style={containerStyle} >
          <h1>Hello</h1>
        </div>
      );
    }
    

    【讨论】:

    • 非常感谢,我想我更喜欢使用第二个选项来保留 App.js。
    【解决方案2】:

    如下更新你的风格:

    .container {
      height: 100vh;
      width: 100vw;
      background-size: cover;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      overflow: hidden;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2022-10-23
      • 2018-04-22
      • 2020-08-13
      • 2016-12-31
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多