Changing the percentage height of a background image to pixels height when the window is resized

My goal is to have a vertical image fill 100% of its div container when the page loads. Everything works perfectly until I inspect the page or resize the browser window, causing the image to shrink proportionally.

CSS:

body {width: 100%; height: 100%};
.container {width: 50%; height: 100%; position: relative};

.bkg-image {
    background: url("../img/image.jpg");
    background-position: right top; 
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
    height: 100%;
    min-height: 500px;
    width: 100%;
    left: 0px;
    top: 0px;
}

HTML

<body>
<div class="container">
</div>
<div class="container">
    <div class="bkg-image"></div>
</div>
</body>

Initially, I used jQuery to set the image height in pixels instead of percentage once the page loaded. This method worked well, but if the user resized the browser window after loading, the image height remained fixed and did not adjust to its container. So, my question is:

Is it possible to maintain the initial functionality, where the image adjusts its height dynamically, even when the browser window is resized?

  • If the browser window is enlarged, convert the height back to 100%, then revert to pixels after resizing is complete.
  • If the browser window is shrunk, stick with the existing jQuery solution.

Is there a way to achieve this desired behavior?

Answer №1

To achieve this, utilize the window.resize() function to dynamically adjust the page layout based on window size changes. For detailed information and examples, visit the following link: https://api.jquery.com/resize/

Here is a simple example of how to use it:

$(window).resize(function(){
    var windowHeight = $(window).innerHeight();
    console.log(windowHeight);
});

For more precision, consider using media queries to target specific window widths.

Answer №2

To achieve the desired effect, consider using the attribute: background-size: cover;

Answer №3

While I may not be an expert in javaScript, I managed to find a solution without posting messy code. My inspiration came from two sources:

  • The first source was this helpful answer on Stack Overflow, which introduced me to $(window).height() and $(window).resize;
  • Additionally, I discovered a simple yet effective plugin called jQuery afterresize event plugin. This allowed me to apply changes only once the resize action is completed, rather than continuously while dragging.

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 CSS perspective shape link is not functioning correctly

I'm attempting to create a trapezoid shape using CSS to contain a link, but it doesn't seem to be functioning correctly. I'm unsure if it's due to lack of support or if there's an issue with the code itself. It looks like it should ...

Parsing DOM data from an HTTP request in Node.js

Looking to extract data attributes from an SVG element on github.com/profile_name using a node.js HTTP request, and then parsing it into JSON format. <rect class="day" width="10" height="10" x="-36" y="10" fill="#ebedf0" data-count="0" data-date="2017- ...

Tips for positioning 2 React Native elements: have one centered and the other aligned to the beginning

Consider the following React Native styles: var styles = StyleSheet.create({ parentView:{ width: 400, height:150 }, containerView:{ flex:1, flexDirection: 'row', alignItems: 'center', justifyContent: &apos ...

JavaScript formula for calculating dates together

I'm currently developing a PHP program for generating invoices. I'm implementing a datetimepicker to select the invoice generation date and due date. Now, I need the due date field to be automatically populated by adding a specific value to the i ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

Modifying Div Size with Jquery

I am working on populating the div container with square boxes, but I'm having trouble adjusting the size of my #gridSquare div. Despite trying to change its height and width using jQuery, it doesn't seem to work as expected. $('#gridSquare ...

Using CSS units such as vw, vh, or percentage to specify height is not possible

In my Ionic app, I am adjusting the width and height of a div based on the viewport dimensions. This setup functions correctly on the browser and Android 4.4 devices. However, it does not work as expected on Android 4.2 (the height is constrained to the te ...

What is causing this to function properly on Firefox but not on Chrome or IE?

After clicking the process_2banner button on my html page, a piece of code is executed. Surprisingly, this code performs as expected in Firefox, but not in Chrome or Internet Explorer. In those browsers, although the ajax code is triggered, the div spinner ...

An adaptive image-based menu design that adjusts based on screen size

Although I can get it to function properly, the trouble arises when I attempt to resize it for responsiveness, resulting in a strange scaling issue. Essentially, I want the images to remain at their natural size and align next to each other seamlessly with ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

What is the best way to retrieve distinct id values from a form in Rails when sending a DELETE request via AJAX?

I am determined to grasp the intricacies of AJAX and how it operates, hence, I prefer not to use "remote: true" for this task. The issue at hand is that despite attempting to send a DELETE request to the server using a form input, each submission results i ...

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...

Deactivate a component in React Js

Starting out in the world of react Js and looking to disable certain elements based on conditions Within my form, I have a select element and two input elements Depending on the selected item, one of the input elements should be disabled Here is a snipp ...

Every time I click the highlight button, my navbar link inexplicably shrinks

I am struggling with adjusting the list style in my bootstrap navbar. Whenever I click on the highlight button, it squeezes my navbar and I'm not sure how to fix it. <div id="links"> <a href="index.html">Home& ...

Controlling ASP/ASPX Label Visibility using JavaScript

I'm currently struggling with changing the visibility of a label when a button is clicked. The label should initially be hidden and then appear after the button is clicked. My attempts using DevEx controls and the SetVisible() function have not been ...

Safari is having trouble correctly displaying a CSS3 gradient with transparency

Here's a tricky puzzle for you. The gradient below is not displaying correctly in Safari, but it works perfectly fine in Firefox and Chrome: background: linear-gradient(transparent 124px, #de6230); I've even attempted the following fix without ...

positioning two out of three items in a navigation menu to the right and the remaining one to the left

I am looking to design a navigation bar that spans the full width of the screen, with the logo on the left side serving as a link back to the home page. Additionally, I want to include elements for register/login and cart. The background color should cove ...

Is it possible to use an :after background-image to layer on top of the following element?

Seeking assistance on adding an image as a :after element to a navigation bar. The goal is for the image to cover the top portion of the next section according to the design. I have set the :after element as position: absolute with a top: 100%, but it app ...

Is there a way to disable certain CSS features in Chrome, like CSS grid, for testing purposes?

I'm exploring alternative layouts for my app in case CSS grid is not supported. Is there a way to disable features like CSS grid in Chrome or Canary? ...