Steps for designing a complete background picture

Seeking to enhance my CSS skills, I've been faced with a challenging task recently.

The objective is to create a full-screen background image with centered text overlay. However, the image appears larger than the screen itself.

This is my current setup:

My App.js

import React, { Component } from 'react';
import background from './images/background.jpg';
import './App.css';

export default class App extends Component {
  render() {
    return (
      <div>
        <div className="App-header">
          <img src={background} className="App-background-header"/>
          <div className="App-header-text">
            <p>This text should be center on the image above.</p>
          </div>
        </div>
        <div>
          <p>This is a sample text after the image...</p>
        </div>
      </div>
    );
  }
}

My App.css

.App-header {
  height: 100%;
}

.App-background-header {
  height: 100%;

  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.App-header-text {
  color: #444444;
  text-align: center;
}

I aim for something like this:

Current result: https://i.stack.imgur.com/EKZ6W.jpg

-- EDIT: --

I managed to resolve the issue but unsure if it's considered best practice.

Here is the updated code:

App.js:

import React, { Component } from 'react';
import './App.css';

export default class App extends Component {
  render() {
    return (
      <div>
        <div className="App-header">
          <div className="App-header-text">
            <p>This text should be center on the image above.</p>
          </div>
        </div>
        <div className="App-divider"></div>
        <div>
          Just a random text here...
        </div>
      </div>
    );
  }
}

App.css:

.App-header {
  height: 100%;
  width: 100%;

  position: absolute;

  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url('./images/background.jpg');
}

.App-header-text {
  color: #aaaaaa;
  top: 50%;
  position: relative;
  text-align: center;
  font-size: 30px;
}

.App-divider {
  height: 100vh;
  width: 100%;
}

The presence of "App-divider" may not be ideal, but it serves its purpose effectively.

Answer №1

If you want to display your image as an img element in HTML, use the following code:

<img src={background} className="App-background-header"/>
. This means that the styling from CSS will not be applied to the image.

To ensure proper styling, update your CSS by replacing .App-background-header with:

.App-background-header img {
  position: relative;
  width: 100%;
  height: auto;
} 

.App-header-text {
  position: absolute;
  top: 50%;
  left: 50%;
  with: 200px;
  height: 200px;
  margin-left: -100px;
  margin-top: -100px;
  text-align: center;
}

Alternatively, you can set your image as a background using the following CSS:

.App-background-header img {
  width: 100%;
  height: auto;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url("your_path_to_image.jpg");
} 

Remember to remove this line from your app.js file:

<img src={background} className="App-background-header"/>

Answer №2

Using an image in your design requires it to blend seamlessly with the style of your App-header. To achieve this, apply the CSS property background-image: src(imagePath)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Bootstrap image alignment problem with columns on extra small screens

My website showcases screenshots of my software in a div element. Everything looks great on larger screens, but once I switch to a phone or resize the window, the images don't align properly, leaving empty space. Refer to the image below for clarifica ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...

Issues have been identified with the performance of Ionic Material List when used in conjunction with ng

In my project involving the Ionic floating menu button, everything is working fine. However, I have encountered an issue where when I click on the + button, I do not want to be able to click on the click me button while the menu is open (Req1.png)https://i ...

Cannot send action using redux-toolkit

                I've been exploring redux-toolkit and I'm puzzled as to why the Add All Products button isn't adding all the products to the redux store's state. Interestingly, the add to cart functionality works perfect ...

Issue with Bootstrap 4 nav bar where the first nav item is not highlighted and a problem with scrollspy

I have encountered an issue that I need help resolving. My Bootstrap 4 navbar has scrollspy enabled to update as you navigate through the page's sections, and a jQuery function provides smooth scrolling when clicking on navigation links. However, I am ...

Could someone please assist me in configuring Autocomplete (MUI) to display my options?

A friend of mine is experiencing difficulty with getting Autocomplete to display anything. Here's the code snippet in question: var names = []; const schoolList = async () => ( await axios.get("http://localhost:5000/api/grabUnivNames/") ...

Guide to redirecting to a page after successful login with NextAuth

After a successful login, I would like to redirect the user to a specific page instead of just going back to the index page. For example, when a user enters the correct credentials, they should be redirected to dashboard.js. index.js <main> ...

organizing the elements in the list into a visually appealing layout

I am currently working on transforming table data into a pivot format and presenting it in a horizontal list. My goal is to ensure the design is responsive enough to be viewed on mobile devices as well. Below you can find the CSS code I have implemented fo ...

Can CSS3 animations be executed sequentially for each child element?

Have you ever tried creating a CSS3 animation in HTML? You can check out an example here. <div class="parent"> <a href="#">First</a> <a href="#">Second</a> <a href="#">Third</a> </div> With the ...

Creating a CSS binding for width: a step-by-step guide

I have a complex layout with multiple elements in different divs that need to be aligned. Hardcoding the width or using JS on page load to specify values in pixels both seem like messy solutions. How can I achieve this without causing a zigzag effect? Her ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

The left-floating elements are only partially functional

I recently encountered an issue with my HTML page that features a basic image gallery enhanced by lightboxes (fancybox). The images are meant to align left, with the first row containing three images and the second row containing two. <div class="image ...

Conceal the toolbar element if it is not at the top of the page

I am encountering an issue with my toolbar. When I scroll down, the transparent background of the toolbar disappears and it looks like this: . How can I hide this component when the page is scrolled down and show it again when scrolling back up to the top ...

What is the best way to increase a state in React?

Currently, I am delving into the realm of React and facing a relatively simple challenge: to create a counter that increments when a button is clicked. However, there seems to be an issue with my component. It appears to treat numbers as strings and conca ...

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Unable to prevent ordered lists from overlapping with other content I attempt to place beneath them in HTML

function filterImages() { let input = document.getElementById('searchbar').value; input = input.toLowerCase(); let images = document.getElementsByClassName('gallery'); for (let i = 0; i < images.length; i++) { ...

Error: The request could not be completed as the server responded with a 404 status code. The error code is ERR_BAD_REQUEST. Please check the request configuration and try again

Seeking to retrieve React Data from an API for my website, I utilized Axios to make a get request in React (home.jsx) to connect with my Express server file (database.js), which fetches information from my Mongo database. However, upon submitting input on ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...