Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window?

You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/

I would like the image to be already scaled vertically when the browser loads.

Currently, the scaling only starts when the onBrowserResize event is triggered.

However, during resize, the image appears to be stretching and warping, and I need to maintain its proportions.

I believe JavaScript holds the solution, but my understanding of it is limited. Any assistance would be greatly appreciated.

Javascript Code:

$(window).resize(function(){
  $('.slide img').css({
    maxHeight: $('.slide').height() * 0.8,
    maxWidth: $('.slide').width() * 0.8
  });
});

CSS Code:

#slide {
    text-align: center;
    background-color: green;
    height: 100%;
    width: 100%;
    display: inline-block;
    }

.slide {
    vertical-align: middle; 
    display: table-cell;
}

.slide:after {
    content: ' ';
    height: 100%;
    display: inline-block;
    vertical-align: middle
}

.slide img {
    vertical-align: middle;
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
} 

HTML Code:

<div id="slide" class="slide"><img src="image.jpg"></div>

Answer №1

Check out the latest version of the Fiddle

No need to rely on Javascript this time.

Avoid stretching the img by not applying width and height directly to it.

Let CSS work its magic:

#slide {
    text-align: center;
    background-color: green;
    height: 100%;
    width: 100%;
    display: inline-block;
}

.slide {
    vertical-align: middle; 
    display: table-cell;
}

.slide:after {
    content: ' ';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}

.slide img {
    vertical-align: middle;
    max-width: 100%;
    background-color: blue;
    padding: 10%; //this is the key
} 

Answer №2

This example perfectly demonstrates the desired outcome, achieved without the use of JavaScript!

Check out this CodePen link for reference.

For those looking to achieve a similar result, here is the modified code snippet:

.slide img {
    vertical-align: middle;
    max-width: 100%;
    max-height: 100%;
    width: auto;
} 

Answer №3

Have you considered utilizing CSS3 properties such as background-size: cover or background-size:contain?

You could try implementing something similar to this:

<div style="width:100%; height:100%; background-size:cover; background-image:url(YOUR_IMAGE.jpg);"></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

Is it possible to use jQuery to update CSS styles in an AJAX request

Is it possible to update the CSS of divs that are injected into files but do not exist in the main HTML file? In my main HTML file, I have: <div id="container"> <div id="page"> <!placeholder> </div></div> I am having tr ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

Decimal error causing Bootstrap grid column division issue

I've been attempting to divide the Bootstrap grid column into 20 grids using the code below: <div style="width: 4.999999998%; margin-top: -27.5px; margin-left: 25px;" class="col-md-.6 col-sm-6"> <div style="height: 32.5px; ...

A mock or spy must be used for the jest function

I'm having an issue with the last expectation not being called in a test I'm writing to test the actions within my application. const pushData = jest.fn(() => Promise.resolve()); test('anotherAsyncCall is fired to get more info', ( ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

Setting up the permanent class path for Nodejs in Linux Mint

Recently, I attempted to install Nodejs Version 6.9.4 on my Linux Mint system using the following steps: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv ...

Centering text within a dynamic div can help create a visually appealing design

While browsing through various forums, I noticed several questions on stackoverflow that touch upon a similar issue to mine. However, my particular problem is a bit unique, and despite my best efforts, I have not been able to find a solution yet. It's ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

What is the limit of CSS includes that IE can process?

While working on theming Drupal, I encountered an unusual issue. After enabling a few modules that added 5 to 10 link tags to the page, I noticed a strange behavior in different browsers. Firefox successfully added the new stylesheets to the cascade, but i ...

Preserve the scroll location while adding new content to a list in AngularJS

I have been attempting to add new items to a list within a scrollable container using ng-repeat, with the most recent item appearing at the top. It is important that I am able to preserve the scroll position if the scrollbar is not at the very top when add ...

Create the columnHeader to match the width of the CSS column

Here's what I attempted: http://codepen.io/helloworld/pen/BcjCJ I aim for each column to have the same width as the column header visually. Currently, a slight difference in width exists between the column header and the actual column. Refer to the ...

The phenomenon of componentDidMount being triggered before the DOM is fully mounted arises when utilizing createPortal in React

I have written a React code snippet that looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) ...

Steps for organizing an array based on unique requirements

My goal is to retrieve an array that consists of the first and second objects based on the "point" property of each object I have a specific condition where if it is satisfied, the positions will be swapped. Default: ENGLISH[0] ENGLISH[1] MATH[0] MATH[1] ...

Error: Unable to access the 'sid' property because it is undefined

I've been facing an issue where sending an SMS through Twilio's API Explorer works fine, but fails under my node installation. Despite a complete uninstall and reinstall, the problem persists. Error 7 Oct 21:28:37 - [nodemon] starting `node scr ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Can Express.Multer.File be inserted into a FormData object easily?

Can anyone assist me in figuring out how to add a file of type Express.Multer.File into a FormData object? Situation: I have received a file with the type Express.Multer.File (I am using nestjs and followed this part of the documentation: https://docs.nes ...

What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the fi ...