Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using:


var wh = jQuery(window).innerHeight();
var ww = jQuery(window).innerWidth();
var fh = jQuery('.drop').innerHeight();
var fw = jQuery('.drop').innerWidth();

However, I can't seem to figure out where I went wrong. I also attempted to adjust for window resizing with:


jQuery(window).resize(function() {
    var wh = jQuery(window).innerHeight();
    var ww = jQuery(window).innerWidth();
    var fh = jQuery('.drop').innerHeight();
    var fw = jQuery('.drop').innerWidth();
});

Even after resizing the window, the image still doesn't align to the center as intended. Is there a method to ensure that the image remains centered even when the window size changes?

You can view the code on JSFiddle.

Answer №1

Why not give this a shot:

$(window).resize(function () {
    $('.drop2').css({
        position: 'absolute',
        left: ($(window).width() - $('.drop2').outerWidth()) / 2,
        top: ($(window).height() - $('.drop2').outerHeight()) / 2,
    });
});

See it in action here

Answer №2

If you want to achieve this effect using only CSS, you can follow these steps:

div{
  background: red;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
}

View the demo on Fiddle and Read more about centering elements with CSS in this Article

Answer №3

This is how I implemented it in my project.

.side {
height: 357px;
background-color: red;
overflow: hidden;
position: relative;
}
.middle {
position: absolute;
left: 50%;
margin-left: -250px;
background:url('a.jpg') no-repeat;
width:500px;
height:357px;
}


<div class="side">
<div class="middle"></div>

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

Issue with ReactJS not applying classes based on conditions

I'm currently working on toggling a class on an element when a user clicks. However, I am facing an issue where my code only sets the class for a single element and does not refresh for subsequent clicks. Even though the set class is not being removed ...

How to refresh an image in Next.js using setState even when the src path remains unchanged

Define a state variable: const [picture, setPicture] = useState(null); Assuming the picture is initially set to "123" and even after updating the image, the value remains "123". How can I reload the Image? <Image src={profileurl + picture} alt="profile ...

Locate a specific data point within an array of JSON objects

After receiving an array of JSON objects from JSP, I now have a set of data that contains book titles. "Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "B ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Saving a picture from browser cache to the server

Following the guidance provided in this thread Preview an image before it is uploaded, I was able to implement a feature on my website that allows users to preview images before submitting them. I currently have code set up to display the image preview on ...

Using CSS Zoom / Transform with the iframe Tag in HTML

I'm currently working on embedding a child web page (a plain HTML/PHP file) into a parent web page built on WordPress. The challenge I'm facing is that the parent web page has a width of only 800px, whereas the child web page has a width of appro ...

Height that is determined in real-time

I am attempting to adjust the height of a div based on the size of the screen. Within this div, there is a calendar that contains multiple lines of content, which can be displayed or hidden based on user preference. The height of the calendar is not fixed, ...

H3 Element Without ASP Causing Disruption in Page Layout

Looking at my .aspx page, I have the following code: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="BootStrap.css" rel="stylesheet" type="text/css" /&g ...

Tips for disabling automatic scrolling when a browser is reloaded using JavaScript

In today's world, most browsers automatically adjust the window scroll position upon page refresh. While this is generally a helpful feature, I find myself in a situation where I need to reload a page and direct focus to a different part of the page t ...

Hello there, could you please point out where the error is located in this code?

$(document).ready(function(){ $('#nav-b .navbar-item li a').click(function(){ $('#nav-b .navbar-item li a').removeClass('active'); $(this).addClass('active'); }); }); < ...

JavaScript's Ajax request seems to be stagnant and inactive

Having some difficulties with the code below. It triggers an alert correctly, but the ajax part doesn't seem to be functioning. No errors or indications of what's wrong. $(document).on('change', '.department_select', function ...

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

Maintain text while transitioning to another page

On my webpage (refer to image for details), users need to select options through a series of steps. The process involves clicking on a link in the top box, then entering a search term in the searchbox to display relevant links in div1. Clicking on a link ...

Dealing with a cross-domain web method that returns a 204 status code

I have implemented a Webmethod in ASP.NET and am attempting to access it through jQuery AJAX. When I request the Webmethod directly via browser, I receive a JSON response. However, when I make the call using jQuery AJAX, I am seeing "204 no content" in Fir ...

Is it possible to keep content visible in Bootstrap tab by adding CSS?

Having an issue with the "formbox" class that is causing unexpected behavior when applied to a form. When removed, everything works as expected. I've tried narrowing down the issue by removing each CSS rule individually and testing it out but haven&ap ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...