Resizing the background while scrolling on a mobile web browser

My website background looks great on desktop, but on mobile (using Chrome) the background starts to resize when I scroll, mainly due to the browser search bar hiding and reappearing upon scroll.

Is there a way to prevent my background from resizing? Check out this video of what happens on my mobile:

Here's the code:

html {
  height: 100vh;
  margin: 0;
  width: 100%;
}

body {
  margin: 0;
  height: 100%;
  ;
  width: 100%;
  background-image: url("https://ogden_images.s3.amazonaws.com/www.observertoday.com/images/2020/08/29003327/SUNSET-579x840.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

#header {
  width: 100%;
  height: 50px;
  background-color: black;
}

#header img {
  height: 6rem;
  margin: 1rem;
}

#content {
  width: 70%;
  margin: auto;
  background: yellow;
  overflow: hidden;
}
<body>
  <div id="header"></div>
  <div id="content">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis necessitatibusaspernatur accusamus, sit exercitationem nostrum itaque sed consequaturperferendis iusto maiores possimus saepe numquam pariatur? Labore excepturitotam id ipsum. (Text repeats multiple times)
  </div>
</body>

I came across a similar question here: Stack Overflow - Background Image Jumps on Mobile Browser, but the solutions were not effective for me as they were outdated. Any new suggestions, preferably using only CSS or vanilla JavaScript if absolutely necessary?

Answer №1

The root cause lies within the background-position:fixed property intended to adjust according to the browser window size (excluding the address bar area).
The solution involves implementing a sticky background technique.
I have verified the code below, and it should maintain its dimensions when scrolling on mobile browsers.

html,
body {
  margin: 0;
  width: 100%;
  max-height: 100%;
  max-width: 100%;
}

#header {
  height: 50px;
  width: 100%;
  background: black;
}

#rest {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  background: blue;
}

#content {
  width: 50%;
  z-index: 0;
  grid-row: 1;
  grid-column: 1;
  margin: 0 auto;
  background: yellow;
}

#sticky_back {
  width: 100%;
  height: 100vh;

  grid-row: 1;
  grid-column: 1;
  position: sticky;
  top: 0;
  background-image: url("https://ogden_images.s3.amazonaws.com/www.observertoday.com/images/2020/08/29003327/SUNSET-579x840.jpg");
  background-repeat: no-repeat;
  background-size: cover;
}
<body>
  <div id="header"></div>
  <div id="rest">
    <div id="sticky_back"></div>
    <div id="content">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis necessitatibus aspernatur accusamus, sit exercitationem nostrum itaque sed consequatur perferendis iusto maiores possimus saepe numquam pariatur? Labore excepturi totam id ipsum. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis necessitatibus aspernatur accusamus, sit... [truncated for brevity]
  </div>
  </div>
</body>

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

Clicking the button will remove any previously applied CSS style using jQuery

Is there a way to remove the background color that was applied to a previously clicked button when clicking on another button? The current code successfully changes the background color of the clicked button upon hover, but it doesn't reset or remove ...

CSS - image does not adhere to max-height when placed in a fluid container - link to jsFiddle

For instance: http://jsfiddle.net/vjqjv/7/ I am facing an issue with an image inside a container (refer to #slider-section in the jsFiddle) that has a fluid height and a set max-height. I have defined max-height and max-width for my image as 100% (check ...

How can I retrieve the selected items from a Listbox control?

Currently, I am working on an ASP.NET application using C#. One of the features in my project involves a Grid View with a Listbox control. The Listbox is initially set to be disabled by default. My goal is to enable and disable this control dynamically bas ...

Ensure that Bootstrap collapse is opened on desktop devices but closed on mobile devices

Is there a way to make a collapse open on desktop and closed on mobile using only Bootstrap? On Desktop: https://i.sstatic.net/IwHCv.png On Mobile: Here, the content should only be displayed when you click on the title of each group https://i.sstatic.n ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

When a user clicks on an anchor tag in a React component, the input element will automatically receive

I am currently working with two components: Within my parent component, I have the following set up: // Initialize focus object as false // Import Child Component and React libraries const parent = React.createClass({ getInitialState: function() { ...

Searching for a table element and clicking it based on its text with Protractor

<tr id="item" ng-repeat="item in itemList> <td id="code" ng-repeat="column in columns">Different Text</td> </tr> I have encountered some similar issues before, but I am still struggling to find a solution. Here is what I have at ...

Customizing Styles in Material UI with React

I am facing an issue with customizing the styles in my Material UI theme in React. Specifically, I am trying to modify the border of the columnsContainer but it doesn't seem to work, only the root style is having an effect. Take a look at this Codesa ...

Is it possible to modify the background color of a checkbox?

I am looking to modify the background color of the checkbox itself, specifically the white square. I have spent a lot of time researching this topic but most articles suggest creating a div and changing its background color, which does not affect the whi ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Utilizing the require function to implement an AngularJS Controller without having

I've been working with requireJS in my application. Every time I try to register a controller on my module, it gives me an error saying that the controller is not defined. Here's the code for my LoginController located in login.controller.js: f ...

Invoke the function when you finish typing in React.js

After I finish typing, I want to execute some code. I attempted to use the following script but it didn't work as expected const stopTypingHandler=(e)=>{ let time; clearTimeout(time); time = setTimeout(() => { console.log("click& ...

Display information upon the clicking of a button and update the color of the selected button

When a button is pressed, I want to display content and change the color of the active button. Currently, I can do each operation individually, but I'm struggling to merge these functionalities. This is how my script looks like for displaying the con ...

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

Items on the list will not be displayed side by side

I am facing an issue for which I cannot find a solution. While creating a Drupal site, I am trying to arrange these list items side by side. Each item has a width of 45%, so theoretically it should be possible to have 2 items next to each other. However, ...

What is the best way to target the shadow DOM host element specifically when it is the last child in the selection?

I want to style the shadow DOM host element as the last child. In this particular situation, they are currently all green. I would like them to be all red, with the exception of the final one. class MyCustomElement extends HTMLElement { constructor() ...

React-select: The default values will only be updated if they are initially set statically

Need help displaying a list of interests from backend data: profile : { interest: ["interest1", "interest2"], }; This is my implementation: import Creatable from "react-select/creatable"; class EditProfileInSettings exten ...

PHP: Converting messy CSV data into beautifully formatted HTML tables

My client regularly sends CSV text files to my PHP application, where the elements in each row follow a consistent format but the commas that separate them vary. This inconsistency poses a challenge when trying to extract data and present it in an HTML tab ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...