How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code:

html, body {
  margin: 0px;
  padding: 0px;
}
body
{
    background-color: #767676;

}
#wrapper {
    position: absolute;
    min-height: 100%;
    width: 100%;
    background: url('back.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    border: 0;
    background-size:100% auto;
}

However, the height shrinks and there is no vertical scroll. How can I fix this?

Answer №1

Is it a good idea to use the background property in the body element?

body {
    background: url(back.jpg) no-repeat fixed center center;
    background-size: 100%;
}

Check out this demonstration on jsFiddle: http://jsfiddle.net/Kqkyb/2/

UPDATE:
I made changes to keep the image fixed at the top of the viewport instead of scrolling with the page.
UPDATE 2:
After reviewing your requirements, I adjusted the CSS to ensure the image is centered both vertically and horizontally. This change has been reflected in the code and the fiddle link provided.

Answer №2

After a restless night, I finally found the solution to my problem by combining two ideas:

  1. Scaling a div to fit in window while preserving aspect ratio
  2. Using well-known techniques, particularly the first one from this source http://css-tricks.com/perfect-full-page-background-image/

Here is the HTML code:

<div class='image'>
     <div class="content"></div>
<div>

And the CSS code:

.image{
    position: relative;
    display: inline-block;
    width: 100%; 
}
.image::after {
  padding-top: 66.66%;
  display: block;
  content: '';
}
.content {
  position: absolute;
  background-image: url('../img/image.png');
  background-size: cover;
  top: 0; bottom: 0; right: 0; left: 0;  /* follow the parent's edges */

It's important to note the following:

padding-top: 66.66%;

This percentage is based on the width of the containing block and depends on the aspect ratio of your image. In my case, I used an image with dimensions of 1920x1280, so the calculation was 1280 / 1920 = 0.6666666. The end result is fully responsive, scales to any resolution, and crucially, vertical scrolling is enabled!

Answer №3

 $("#container").css({'height':($("body").width() * 375 / 589 +'px')});

375 / 589 - represents the aspect ratio of my photo. Whenever the browser is resized, the image's width changes, so I need to recalculate the height to ensure it remains proportional.

I am hopeful that there is a CSS solution available for this issue.

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

The never-ending scrolling problem: Autoscroll refusing to halt - a perplexing conundrum in the world

I'm having an issue with my chat box continuously autoscrolling and not allowing me to scroll up. I know where the problem is, but I'm unsure of how to resolve it. Ideally, I want the chat box to autoscroll while still maintaining the ability to ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

How can I create a delay in the background using jquery?

I've been attempting to change the background of certain divs on hover using jQuery, but I can't seem to get it to work. What I'm looking for is an effect that smoothly transitions from one image to another upon hover, as the CSS transition ...

Determine the hour difference between two provided dates by utilizing the date-fns library

My API returns a "datePublished" timestamp like this: "2019-11-14T14:54:00.0000000Z". I am attempting to calculate the difference in hours between this timestamp and the current time using date.now() or new Date(). I am utilizing the date-fns v2 library fo ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

Maximizing the potential of NPM modules by harnessing the power of the package.json file

Currently, I am working on developing an NPM module for a command-line tool. Upon installation of the package, it is essential to access and read the user's package.json file. While I understand how to read the file syntactically, my main concern lies ...

The body can only stretch up to a certain percentage of its width, not a full 100%

Recently, I've been encountering an issue with my webpage where the body does not stretch 100% the width of the screen. I've tried numerous CSS rules to fix it, but nothing seems to be working. When you view the page in a browser, it appears to c ...

A straightforward jQuery conditional statement for dynamically generated content

If the div '#ajax' contains content, I want to make the div '.container' clickable. Here is the basic jQuery script I have implemented: if ('#ajax:empty') { $('.container').css('pointer-events', ' ...

The input type file is not correctly inserting an image into the image tag

While I was working on a project, I had a question that got answered but now I need to find a different way to use the solution. I have created a jsFiddle to demonstrate how it currently works. You can view it here: http://jsfiddle.net/TbZzH/4/ However, w ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

Unexpected resizing of a div due to Vue animation

I'm currently working on a quiz and I'm trying to incorporate some animation effects when users navigate between questions. I've been experimenting with a fade in and out effect, but there seems to be a glitch. Whenever I click the button, t ...

Why is it that the date selector is missing in Firefox?

When using the provided HTML code, a date selector will appear on Google Chrome: <html> <head> <title> </title> </head> <body> <form> <input type="date" /> </form> </body> However, ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

Random image generator using jQuery on the home page body

Hey guys, I'm working on a cool feature for my Wordpress site where a random background image loads every time the homepage is refreshed. Check out the code snippets below: First, here's what I have in my style sheet (style.css): body.home { ...

I'm encountering an issue with my API Key being undefined, despite having it saved in both an .env file and as a global variable

While attempting to retrieve information from an API, I encountered an issue where the key I was using was labeled as "undefined". However, after manually replacing {key=undefined} with the correct string in the network console, I was able to successfull ...

Display the same data point on a Google Map from two different rows of a database

I'm looking to display multiple values for profFName and profLName on a map with just one point showing this information. If I have (2) pID connected to the same marker, I want it to show both profFName and profLName on a single point. Currently, it ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

What is causing the default switch to constantly loop in repetition?

Currently, I am working on a Discord bot using discord.js and utilizing a switch statement. However, I am encountering an issue where the "default:" case keeps repeating itself every time any other case is executed. I have already investigated for cases w ...

Alignment issue with text in Vuetify Datatables cells

I'm experimenting with Vuetify on my Laravel Vue application, and everything seems to be working fine except for the DataTables styles. The padding of the cells is not vertically center aligned as expected. Here's a screenshot Interestingly, the ...