What techniques can be used to resize an image to perfectly fit a square on a webpage?

A challenge on the web page is to display images in a square format of 90 * 90 pixels. However, the sizes of these images are not consistent and may vary from 80*100 to 100*80 or even 90 * 110.

The requested solution is to stretch the image as follows:
1) If an image has a width of 45 and height of 100, it should be stretched to a width of 90 and height of 200 while displaying only the top 90 pixels.
2) If an image has a width of 100 and height of 45, it should be stretched to a width of 200 and height of 90 while displaying only the left 90 pixels.

In essence, the aim is to always show the top-left portion of the image within a 90*90 size frame.

What would be the solution for achieving this using JavaScript and CSS? Thank you

Answer №1

Would this code work?

<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;background-image:url('myImage.jpg');background-size:100%;"></div>

For an example, visit

UPDATE:

I have updated the implementation to use JavaScript instead of CSS. This should resolve any issues with incorrect display of width and height when using CSS only. Check out the example at .

<script type="text/javascript">
function fitImage(src) {
    var image = new Image();
    image.src = src;
    var height = image.height;
    var width = image.width;

    if(width > height) { // Image is wider than it's tall
        scale = 90 / height;
    }
    else { // Image is taller than it's wide
        scale = 90 / width;
    }

    image.width = width * scale;
    image.height = height * scale;

    document.getElementById('info').innerHTML = width + 'x' + height + ' => ' + image.width + 'x' + image.height;

    document.getElementById('container').style.backgroundImage = 'url(' + image.src + ')';
    document.getElementById('container').style.backgroundSize = image.width + 'px ' + image.height + 'px';
}
</script>
<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;" id="container"></div>
<div id="info"></div>
URL for an image: <input type="text" id="url" style="width:400px;" />
<br />
<input type="button" value="Fit images" onClick="fitImage(document.getElementById('url').value)" />

Answer №2

All you have to do is specify the required width and height within the image html tag as shown below

<img src="myphoto.jpg" width="150" height="150"/>

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

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

Navigating to a specific element following an AJAX request

Can't seem to get the page to scroll to a specific element after an ajax call. What could be causing this issue? index.php <style> #sectionOne { border: 1px solid red; height: 100%; width: 100%; } #sectionTwo { border: 1px solid blue; heigh ...

Adjusting the text color of cells in a table based on their values using Ruby on Rails

I have a cell within a table that is formatted like this: <td><%= play_result.timestamp.strftime("%H:%M:%S") + ' ' + play_result.status + ':' + ' ' + '[' + play_result.host + ']' + ' ' ...

What is the best method for initializing the value of ng-model as an empty string in AngularJS?

I need help setting the initial value for an attribute in my model. Here's the code I'm using: <input type="text" ng-model="selectedModel.title" name="title" value="" > What I want is for the attribute value to be initially set as an empt ...

Understanding the basics of reading a JSON object in TypeScript

Displayed below is a basic JSON structure: { "carousel": [], "column-headers": [{ "header": "Heading", "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id el ...

Ways to modify an object similar to manipulating an array collection

Hey there, I've heard that iterating and editing objects (not arrays) is not the best practice. Is there a more efficient way to do it as easily as it can be done with an array of objects? Check out this link for reference new Vue({ el: '#app ...

issue with non-existent value in v-for loop when using functional template refs

Scenario I am currently developing a personalized filtering feature. This feature allows users to add n filters that are shown using a v-for loop in the template. Users have the ability to modify input values and remove filters as needed. Challenge Issue ...

Encountering an error when accessing dynamically routed pages in Next JS

When I click on a link within the web app to navigate to a dynamically routed page for a product (http://localhost/1), everything works as intended. However, if I manually input a specific product number in the search bar to navigate directly to that page ...

Best practice for finding the parent element using Protractor

The recently released Guidelines advise against using the by.xpath() locators. I am making an effort to adhere to this suggestion, but I'm having difficulty locating a parent element. We are currently utilizing the .. XPath expression to access the p ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

Error with review score in material-ui for react.js

There is an issue with my code where the ratings from different sets are not behaving independently. When a rating in one set is clicked, only the first set of ratings changes, suggesting that there is a connection between all the sets. https://i.sstatic. ...

Tips for incorporating user access control logic into a lazy-loaded Angular Monorepo application without embedding the logic in the main application

In our current project, we are developing an Angular application utilizing the Angular monorepo structure. This setup includes a parent application and several children applications, with the parent application located in the `app` folder and the children ...

Prevent blurring on a sub-element when hovering over a blurred container using Bootstrap 5.2

Can anyone help me prevent a blur effect on the "text-block" child element when the mouse hovers over the card element? I want the card element to have a complete blur effect while also displaying the text block on top of it. I've tried several optio ...

Load page content dynamically with Ajax in a specific div while still allowing the option to open the content in a new tab by right-clicking

As I work on developing a new website that utilizes a MySQL database to sort various items into categories and subcategories, I have implemented a script that dynamically loads category content into a div without requiring a page reload. This seamless load ...

What is the process of creating a deep clone of the state and reverting back in Vuex?

Looking to create a snapshot or clone of an object property within the Vuex tree, make modifications, and have the option to revert back to the original snapshot. Context: In an application, users can test out changes before confirming them. Once confir ...

What is the computed value of HTML and body?

Is there a specific reason why the body tag has a default margin while HTML does not? Could there be any practical explanation for this design choice? ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...

What is preventing this from functioning properly? (html/javascript)

I need help checking if this code is correct, as I am not very knowledgeable about HTML. I would appreciate it if someone could explain it to me in simple terms so I can understand. Here is the code: <input type="text" id="user" value=""> <inpu ...

I'm looking to automate a system response whenever a user inputs something - how can I achieve this using NodeJS and Socket

I'm looking to create a feature where, if a user enters a specific command, the socket.io will respond with a predefined message. For example: Input: !hi Output: hello! If anyone knows how to achieve this, I'd appreciate some guidance, tha ...