Creating an illusion of depth with a parallax effect by enlarging the background beyond the boundaries of its container

I am encountering an issue with my code that is causing white space to appear on the right side of the page due to the background being larger than the container. I am unsure how to resolve this while still maintaining a parallax effect on the background.

Does anyone have any suggestions on how to address this issue?

var lFollowX = 0,
  lFollowY = 0,
  x = 0,
  y = 0,
  friction = 1 / 60;

function moveBackground() {
  x += (lFollowX - x) * friction;
  y += (lFollowY - y) * friction;

  translate = 'translate(' + x + 'px, ' + y + 'px) scale(1.1)';

  $('#home-background').css({
    '-webit-transform': translate,
    '-moz-transform': translate,
    'transform': translate
  });

  window.requestAnimationFrame(moveBackground);
}

$(window).on('mousemove click', function(e) {

  var lMouseX = Math.max(-100, Math.min(100, $(window).width() / 2 - e.clientX));
  var lMouseY = Math.max(-100, Math.min(100, $(window).height() / 2 - e.clientY));
  lFollowX = (20 * lMouseX) / 100; // 100 : 12 = lMouxeX : lFollow
  lFollowY = (10 * lMouseY) / 100;

});

moveBackground();
#home-background {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: url("https://www.tokkoro.com/picsup/5746854-geometry-wallpapers.jpg") no-repeat center center;
  background-size: cover;
  z-index: -1;
}

#menu {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #251524;
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="home">
  <div id="home-background"></div>
  <div id="greeting">
    <h1>Hello</h1>
  </div>
</section>
<section id="menu">
  <ul>
    <li><a href="#home">Home</a></li>
  </ul>
</section>

Answer №1

One of the reasons why the background div is expanding beyond the container's limits is due to the use of transform: translate(...), which moves the background outside the container.

If you wish to move the background but clip its edges to match the container instead of extending it, you will likely need to utilize overflow: hidden. This CSS property prevents elements from showing outside their boundaries.

In your specific code scenario, a simple solution would be to add overflow: hidden to the body element:

body {
  overflow: hidden
}

However, adding overflow: hidden to the body may not be ideal if overflow is required elsewhere on the page. In such cases, wrapping the #home and #menu sections in a parent div with overflow: hidden can contain the background. Remember to also include position: relative for this approach to work correctly.

Here's an updated version of your HTML layout following these adjustments:

<div class="container">
  <section id="home">
    <div id="home-background"></div>
    <div id="greeting">
      <h1>Hello</h1>
    </div>
  </section>
  <section id="menu">
    <ul>
       <li><a href="#home">Home</a></li>
    </ul>
  </section>
</div>

The corresponding CSS modifications are as follows:

.container {
    overflow: hidden;
    position: relative;
}

Below is a snippet demonstrating these modifications:

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

Steps for adjusting an image in a Bootstrap Carousel

Currently tackling a simple bootstrap Carousel for a school project. I've adjusted the max-height of the images to 400px but it seems like only the top part of the images is visible. I attempted to adjust the margins on the image, and even thought abo ...

Make sure the navigation bar is fixed to the top of the page only

Looking for a solution to stick the navigation menu to the top of the screen only when the screen is wider than 782px. Progress so far: https://jsfiddle.net/ah4ta7xc/1/ Encountering an issue where there is an unintended gap at the top when applying the s ...

How to use jQuery to gather all the text from a textarea

Is there a way to automatically select all text inside a textarea when it is clicked on? Additionally, can this selection be deselected by clicking again? ...

Aligning an Image Dynamically Inserted with JavaScript

I'm having trouble centering an image added via Javascript within a table using my embedded CSS. Can someone guide me on how to adjust the CSS to center the image in the table? I've tried setting the margin property to auto for the image, but it& ...

POSTing with AngularJS

My PHP page, submit.php, is designed to take the "data" parameter as either get or post, and save it into a local file. I have confirmed its functionality by testing it with jQuery's $.ajax method. Now, however, I need to integrate AngularJS into my a ...

Ways to extract the content of a particular <span> element stored in a variable that includes the entire HTML page markup

I have extracted the price of bitcoin from a web page and saved the entire code in a variable. How can I specifically retrieve the span element: <span class="text-large2" data-currency-value>8128.61</span> within the code snippet? The value ...

Using jQuery to store the selection made in a select element option

Hello everyone, I need some help with saving the selected option on my form by the user. I am not sure how to accomplish this. Let me give you a brief overview of my setup... On my home page, I have a form that looks like this: <form class="form-home ...

Displaying JSON data received from an AJAX request on the screen

Our server is located in Europe. Occasionally, a user based in America reports an issue when using the $.getJSON function. Instead of passing the JSON response to JavaScript, the user's browser simply displays it. The AJAX call appears as follows: ...

Employing foreach loop for generating hyperlinks from an array

I am seeking assistance in generating links using a PHP foreach loop that cycles through an array containing the names of navbar links for a website. Currently, my loop is creating links that lead to a 404 error page and display unwanted HTML tags in the ...

The Raycaster.intersectObjects function in Three.js is only able to detect intersections with the front surface

My current project involves generating a world filled with blocks on the ground upon mouse click (using mouse click coordinates that I've calculated). To ensure that each new block doesn't intersect with existing ones, I implemented a check using ...

Transferring information from Node.js to React

I am currently converting a component into React code. Previously, I was using Jade to compile it and passing the i18n text from a global in Jade directly to the HTML. The setup looked something like this: // within Node.js / Express const text = require ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

What is the method to have text added automatically to an input field when a key is pressed?

Within my navigation, I have implemented a "full-screen overlay search box". When users click on the magnifying glass icon, a full-screen overlay with a search input field appears. You can see an example image here: . Currently, to enter text in this full ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

Can the height of a container be dynamically adjusted to match the height of its child element with absolute positioning?

My website includes a search field where users can type in their queries. However, I am facing an issue with the autocomplete feature causing layout problems on certain screen sizes. In order to prevent the autocomplete list from affecting the overall pag ...

Show advancement bar during the process of creating an Excel spreadsheet in php

I'm currently working on an HTML form that generates an Excel file using PHPExcel when submitted. Everything is functioning correctly, but I've noticed that the process takes a long time for large excel files. I would like to implement a progress ...

How to Nest Div Elements in Bootstrap Grid System

I'm currently using bootstrap to create the structure for my website. However, I am facing an issue with arranging three div tags within one main div tag. Instead of appearing side by side, they are stacking on top of each other. <div class="col- ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Tips for preventing needless re-renders in React functional components when dealing with "static components"

In my React functional component, I have a feature that displays a list of tags and posts along with some static text and decorations. The currently selected tag is stored in a state using the useState hook. Posts are fetched through Apollo's useQuery ...

"Stable header and footer paired with comprehensive menu navigation spanning the entire length of

I've exhausted all of my options. I've attempted numerous coding examples from various websites and tutorials, but I can't seem to get this to work no matter how hard I try. I'm completely frustrated and ready to give up on figuring it ...