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

Angular JS Retrieving Data in the Background with the Assistance of $timeout or $interval Service

Looking to fetch data from a webapi in the background using either the $timeout or $interval service in Angular JS. I have some concerns about how the $timeout and $interval services work. I've run into issues when incorporating these services into m ...

Invoke a separate function after a successful Ajax request

I am currently working on an AJAX call in MVC3 and here is the snippet of code I have: save: function () { $.ajax({ url: "@Url.Action("Save")", type:"post", data: ko.toJSON(this), contentType:"applic ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...

There seems to be confusion surrounding the $.isArray() function in jQuery

I'm currently trying to determine whether the p array is valid or not. I'm not sure if I'm on the right track or if I'm making a mistake. I am currently studying the jQuery.isArray method. I suspect that there may be an error in my code ...

The horizontal scrollbar in Chrome is unexpectedly activated, despite elements being set to occupy the full screen width (100vw) using Tailwind and NextJS 13.4+

It took some time to identify the root cause of this issue within a larger project. Hopefully, this Question and Answer will be beneficial to someone else. Here is the scenario -- in a NextJS/Tailwind project, there is only one large vertical element on t ...

The resolution of the dynamic imported Vue component was not successful

Upon attempting to import a dynamic component using the import() function, I encountered the following error: [Vue warn]: Failed to resolve async component: function () { return __webpack_require__("./src/components/types lazy recursive ^\\. ...

Use jQuery to redirect the user if the URL does not match

Is there a way to automatically redirect users to a specific page if they are not currently on that page? For example, something like the following pseudo code: if not (url = example.com/index.php) redirect to example.com/index.php /if When a user vi ...

The inner div overflowing at 100% dimensions

I'm working with an outer DIV that has a CSS property of position: fixed to serve as an overlay. Inside this, I have another div set to 100% width with a margin of 30px to create the appearance of an inner border frame. Unfortunately, the right and bo ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

Executing SendKeys on a div element with the attribute coleditable="true" in Selenium and C#

I am facing a challenge with an element that I am unable to input text into. <div class="floatstart gridcell grideditablefield" colname="Items" coltype="string" coleditable="true" val="" style="widt ...

"Develop a mobile application using PhoneGap designed specifically for use on iPad and

Looking to create an app for iPad and iPad Mini using PhoneGap. While I have some basic knowledge of HTML and CSS, I am struggling with adjusting the image proportion, width, and height of the app. I want to write code that will adapt properly to the vary ...

The alignment of the content within a div is mismatched compared to a div that doesn't have any

Can you figure out why the element with content is out of order compared to the other elements without content in the code below? This issue seems to disappear when all elements have content. Any insights on this peculiar behavior? (Thank you in advance fo ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

How can you align a div next to another using the float property in CSS?

/*Custom Styling for Divs*/ #box1 { border: 1px solid; border-radius: 25px; width: 900px; } #box2 { border: 1px solid; border-radius: 25px; width: 430px; } #box3 { float: right; border: 1px solid; border-radius: ...

NodeJs - Uncaught Typeerror: Cannot create an instance of Post

Currently, I am developing a blog application using NodeJs. I encountered an issue when trying to save posts in the database. The error message that appeared after submitting the form is as follows: TypeError: Post is not a constructor index.html <fo ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

How can I align the logo in the center of a ul

Many have attempted to resolve this issue, creating makeshift solutions or simply settling for an outcome that just "gets by." But what is the optimal approach? I have nearly finished something, yet for some reason, the logo isn't centered, rather the ...

Performing an HTTP GET Request in Node.js or Express.js

Currently, I am working with express.js and require assistance in making an HTTP GET request to retrieve JSON data. Can anyone recommend some reliable node js/express js modules or libraries that can help me with performing get/post requests? ...