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

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

Steps for incorporating error messages in jQuery Validator:1. Begin by including the

I am currently facing an issue with displaying error messages on my "contact me" form. Although I have successfully implemented validation, I am struggling to comprehend how the errorPlacement function should be utilized. Could someone provide me with a ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Acquiring inner HTML content with PHP

Looking to optimize meta tags for search and open graph. My goal is to dynamically generate the meta description tag by combining content from two specific elements in the HTML. For instance, let's say we have this snippet of code: <div class="r ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

What exactly is the purpose of the double ampersand selector, '&&', when it comes to overriding the root class with makeStyles within Material-UI React?

I recently started using Material-UI and encountered an issue where I couldn't override the root class for Avatar, specifically MuiAvatar-root. Material-Ui Version: 4.11.3 Despite following examples provided by material-ui's documentation here, ...

Issues arise when props do not get transferred successfully from the getStaticPaths() to the getStaticProps

I have successfully generated dynamic pages in nextJS from a JSON using getStaticPaths(). However, I am facing an issue where I am unable to access the information within the JSON. I pass it as props to getStaticProps(), but when I try to console log it, i ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Replace the hyperlink with plain text using JQuery

Is there a way to replace a hyperlink within an li element with different text but without removing the entire list item? <li class="pull-left"> <a href="#" class="js-close-post" data-post-id="1"> Close </a> </li> ...

Troubleshooting AngularJS Get Function Failure

New to the world of AngularJS, I find myself faced with a challenge. My .NET MVC WebAPI Restful app is up and running on an IIS server. However, when I attempt to query the API using , the response I receive is: [{"Id":1,"Name":"Glenn Block","Created":"00 ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...

JavaScript Autocomplete - retrieving the value of a label

I am looking for a way to utilize the autocomplete feature in my form box to extract a specific value from the displayed label. When a user selects an option, I want to include part of the label (client_id) in the form submission process. JS: <script ...

Shifting the placement of a component in Vue JS when hovering the mouse

I am facing an issue regarding the positioning of components. I have four images, and when you hover over them, a specific component is displayed as shown below: For example, hovering over a yellow image will display a different component below it, and so ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

How to work with a JSON object in Internet Explorer 6

Looking for some quick answers that should be easy for someone with expertise to provide. I have a basic asp.net site that relies on JSON for various tasks (and JSON.stringify). Everything works fine in Firefox and the like, but in IE6 I'm getting a ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Troubleshooting in Next.js 13: Issue with module not being found while trying to reference a package containing CSS

Currently working with Next.js version 13.4.2 and I have included an npm package that comes with CSS styles and fonts. The issue arises when trying to utilize one of the CSS files within my application. In the layout.tsx file, I imported the CSS file as fo ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...