Arranging an image in a specific location relative to its dimensions

I am currently developing a basic script to create a slideshow, inspired by this particular script.

Context:

Many existing slideshow scripts struggle with displaying portrait-style images properly. I am aiming to construct one from the ground up that can handle both landscape and portrait orientations.

Challenge:

My goal is to have the images centered on the page using CSS properties like position:absolute;, left:50%;, and top:50%;. However, achieving perfect centering requires calculations like left:50% - imageWidth/2, which CSS does not support.

Therefore, I need to utilize JavaScript to dynamically adjust the positioning based on the dimensions of each image.

This is the HTML code I am using:

<div class="fadewrapper">
    <div class="fadein">
        <img src="../Content/images/samples/1.jpg">
        <img src="../Content/images/samples/2.jpg">
        <img src="../Content/images/samples/3.jpg">
    </div>
</div>

And here is the associated CSS:

.fadewrapper {width:100%; height:100%;}
.fadein { display:inline-block;}
.fadein img {position:absolute; top:50%;}

While my understanding of JavaScript is limited, I came across this helpful snippet (from Stack Overflow):

var img = new Image();
        img.onload = function () {
            alert(this.width + 'x' + this.height);
        }
        img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

This script provides the image dimensions but I am unsure how to integrate it into my project for adjusting image positions. Any guidance or assistance would be greatly appreciated.

Answer №1

Check out this code snippet for positioning an image in the center of its wrapper.

 var winWidth = $('#fadewrapper').width();
 var winHeight = $('#fadewrapper').height();
 var borderSize = $('#framewrapper').css('borderWidth');
 $('.fadein img').each(function(){
     $(this).css({
         'left' : (winWidth - $(this).width() - borderSize) / 2,
         'top': (winHeight - $(this).height() - borderSize) / 2
     });
 })

Take a look at this jsFiddle to see a working example. The image reacts to window size changes, so try resizing the output window to see it in action.

Answer №2

If you're looking to experiment, give this a shot:

<DIV style="position:relative;top:100px;height:300px;text-align:center;white-space:nowrap">
    <IMG id="your_img_id_1" src="your_img_source" height="100%">
    <IMG id="your_img_id_2" src="your_img_source" height="100%">
    <IMG id="your_img_id_3" src="your_img_source" height="100%">
</DIV>

Apply these positioning rules to your fadewrapper class and remove any others. Adjust the values for top and height as needed, but keep the height attributes in the IMG elements unchanged. Feel free to leave out IDs if they're unnecessary.

UPDATE:

Apologies for not considering window resizing earlier. The code has been fixed. The widths should now adjust properly for smaller window sizes.

I've tested this on IE, FF, Opera, and Chrome, and the images display as intended in all browsers. Let me know if my interpretation of your needs is off!

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's $q.defer() function will yield an object with a "then" function

In my Angular file, I am attempting to access a database using $http and then store the retrieved data in a $scope variable for display on the webpage. However, I am encountering difficulties with $q.defer not running as expected. When I check the consol ...

AJAX cached outcomes

Trying to educate myself on AJAX using w3schools.com, but struggling with a particular example: xhttp.open("GET", "demo_get.asp", true); xhttp.send(); In the above example, there might be a cached result. To prevent this, you can include a unique ID in t ...

Struggling to retrieve a single value from my React app using sequelize findbyPk

Greetings, I am new to this and have a question that may seem silly. Despite my efforts to resolve it on my own, I have been unsuccessful. When using Postman, the data returned to "localhost:8000/playlists/1" is correct, but when I try to access it through ...

Implementing ES6 import syntax in Angular 1.5 application alongside UI Router

I'm working on bringing together Angular 1.5 and UI Router using ES6 import module syntax with Babel & Webpack. Here is an example from my app.js file: 'use strict'; import angular from 'angular'; import uiRouter from 'angu ...

Recently, there has been an issue with the size of SVG images specifically on Android Chrome

UPDATE: I have narrowed down the issue to two SVG images that can be found here: . Strangely, Chrome on Android is displaying the second SVG image underneath the first. Take a look at this screenshot of the incorrect rendering on the Chrome browser for And ...

Progressive form - receiving AJAX response at the succeeding stage

Is it feasible to retrieve the response from step 1 in step 2 of a multistep form using PHP, AJAX, and jQuery? Currently, I am able to receive the response, but it seems to halt the form processing and displays it on the phase 1 form. Just to clarify, I ...

Use Javascript to set cookies and remember the show state when clicked

Can you offer some advice? I am looking to add cookies to my simple JavaScript code. Currently, the div is displayed when clicking on a link, but it hides again when the page reloads. I would like to implement cookies to remember the show state for 7 days. ...

Filter out discord messages for deletion

A script was created to automatically delete messages from offline users during chat sessions on Discord. If an offline user attempted to chat, their message would be deleted, and a notification would be sent to the console indicating that offline chat was ...

Preserve identical elements within an array

I am looking to create an array of key:value pairs, even if there are duplicates present. My goal is to have an array of tasks, where each task consists of multiple operations. I only require the key/value for these operations. Currently, the value of th ...

Using V-For with data fetched from an axios request: A step-by-step guide

How can I dynamically populate V-Cards after making an Axios request to retrieve data? The Axios request is successful, but the v-for loop does not populate with V-Cards. I've also attempted to make the request before the rendering is completed (usin ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Issues encountered with rest arguments while setting up gtag

I am currently working on implementing a Google Tag loading script using TypeScript. const GTAG_ID = 'ID'; const script = document.createElement('script'); script.src = `https://www.googletagmanager.com/gtag/js?id=${GTAG_ID}`; ...

Tips for dynamically adding an HTML element to index.html using JavaScript

https://i.sstatic.net/cAna8.png How can I use JavaScript to insert cards into a container or display them in flex? Currently, the cards are not displaying as desired. I attempted to insert data into the note class using insertAdjacentHTML in JavaScript, b ...

Locate a web address within the text and turn it into a clickable hyperlink

In my content, there are URLs that are not clickable like this example: (). How can I make these URLs clickable using javascript or CSS? The data comes from an API and cannot be fixed. I need to find a solution in the view with CSS or jQuery. ...

What is the best way to include a JavaScript variable in an HTML image src tag?

Even though I know the answer to this question is out there somewhere, I just can't seem to find it (or maybe I'm not recognizing it when I see it!). As a beginner in jquery, please be patient with me. Dilemma: I have a collection of 20 images, ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Having trouble with my NodeJS POST route implementation with Axios

I encountered an issue with my Post route using axios. Upon clicking the button to create a new user, I received the following error message: (node:13901) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined ...

What is preventing JavaScript from parsing this specific string?

When I send a JSON encoded value from PHP to JavaScript and try to log it in the console, this is what I get: {"id":"4","username":"muzikant346","coins":"675","avatar1":"1","avatar2":"0","avatar3":"0","avatar4":"0","avatar_selected":"0"} The issue arises ...

Navigate from the upper left corner to the lower right corner while hovering

Can you animate the movement of an element from the top-left to the bottom-right using CSS transitions like this? #example { width: 40px; height: 40px; background: red; position: absolute; top: 0; left: 0; transition: all 300ms ea ...