Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload photos! The dimensions of the uploaded photo cannot exceed 360px in width and height, with a minimum of 100px, and the maximum height can't go over 200px (with a minimum of 100px).

My question is, can this requirement be met using only CSS? Or would JavaScript be needed? But if JavaScript is necessary, I'm not sure how to get started as my JavaScript skills are quite limited. Any valuable suggestions from you guys would be greatly appreciated, thank you!

I've included an example below. The original photo size is only 50PX in height. How can the photo's height be increased to 100PX without affecting the ratio?

.photo{
  width: 360px;
  height: 200px;
  object-fit:contain;
  object-position:left center
}
<div class="demo">
  <img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>

Answer №1

I believe this is the solution you are looking for.

Make sure that the image has a maximum width of 360px and a minimum height of 100px.

If you need to set additional properties like min-width and max-height, you can include them in the imageSettings variable within your JavaScript code.

For multiple images, simply assign the class imageContainerForJS to the parent element containing the img tag.

(()=>{
    let imgContainers = Array.from(document.querySelectorAll('.imageContainerForJS'));
    const imageSettings = {
        "max-width": 360,
        "min-height": 100,
    }
    
    for(let imgContainer of imgContainers) {
        let img = imgContainer.querySelector('img');
        if(!img) continue;
        let imageSource = img.src;
        let image = new Image();

        let maxWidth = imageSettings['max-width'] || null;
        let minWidth = imageSettings['min-width'] || 0;
        let maxHeight = imageSettings['max-height'] || null;
        let minHeight = imageSettings['min-height'] || 0;

        image.onload = function() {
            let width = this.width;
            let height = this.height;
            
            if(maxWidth && width > maxWidth) width = maxWidth;
            if(minWidth && width < minWidth) width = minWidth;
            if(minHeight && height < minHeight) height = minHeight;
            if(maxHeight && height > maxHeight) height = maxHeight;

            imgContainer.style.width = width+'px';
            imgContainer.style.height = height+'px';
        }

        image.src = imageSource;
    }
})();
.photo{
    object-fit: cover;
    object-position: center;
    width: 100%;
    height: 100%;
}
<div class="demo imageContainerForJS">
    <img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>

Answer №2

To ensure your image perfectly fits its container, utilize the CSS property object-fit: cover.

Specify the dimensions of the container and make the image fill it completely by setting both width and height to 100%.

By default, the cover value will center the image within the container.

.demo {
  width: 360px;
  height: 200px;
}

.demo .photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /*object-position: left center;*/
}
<div class="demo">
  <img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</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

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

Enlarging an image on canvas and creating a repeating pattern

My canvas size is 500px x 500px. I have a png image that matches the canvas size, which you can view here. I am looking to resize the image to 100px x 100px and then use it as part of a repeat pattern on the canvas. This is how I achieve this: // First d ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Position pictures in the same row in a straight line

I am struggling to align a set of images properly. The screenshot below shows the current layout: My goal is to have all four images lined up in a single row, with any additional images starting on a new row. I have attempted various methods, but none ha ...

Displaying only one modal at a time with Bootstrap 3

The code snippet below is used to trigger my newsletter modal: $(window).load(function(){ if (sessionStorage.getItem("is_seen") === null) { setTimeout(function(){ $('#newsletter_modal').modal('show&ap ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Why is Google Chrome cutting off parts of my website?

Has anyone encountered the strange rendering issue in Google Chrome? Check out this bug here http://community.mediabrowser.tv/uploads/site_1/126/annoying_rendering_bug.jpg I sometimes experience it when I visit What is causing this issue? Is there a way ...

Excessive image display | HTML and CSS synergize

I am having some trouble with my image gallery. Each image is displayed as a vertical column and has zooming effects when hovered over. Clicking on an image should show it in full screen with a caption. The problem arises when dealing with images that are ...

Generating a clickable link for a variable within javascript

$scope.msg = "Data Updated Successfully. Item ID: " + $scope.id; After successfully updating any data, a message will be displayed as "Data Updated Successfully. Item ID: 13456". I want to turn the ID into a clickable hyperlink. Here is what I have attem ...

Creating files using the constructor in Internet Explorer and Safari

Unfortunately, the File() constructor is not supported in IE and Safari. You can check on CanIUse for more information. I'm wondering if there's a workaround for this limitation in Angular/JavaScript? var file = new File(byteArrays, tempfilenam ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

What is the best way to show nested labels on separate lines simultaneously?

Despite attempting to utilize the map method as suggested in my research, it appears that it may not be suitable for the structure I am working with: const stepLabels = [ { labels1: ['First One'] }, { labels2: ['Second One', 's ...

animations are not triggering when using ng-click inside ng-repeat, is there a reason why the event is not firing?

Check out the code in jsFiddler here After reviewing the code, it's clear that when the add button is clicked, a new item is pushed to the $scope.p. Each item in the ng-repeat loop has an event-binding and everything functions correctly. However, onc ...

Find all strings in the array that do not begin with a letter from the alphabet

When a specific button is clicked, I need to filter the example array provided in the snippet below. The expected output should only include elements that do not start with an alphabet. I attempted: const example = ["test", 'xyz', '1 test& ...

Is it possible to activate a function in an express application when it is terminated?

I am looking for a way to handle server termination events by dumping data to disk. I'm wondering if there is a better way than logging everything in a database every few seconds using setTimeout. One possibility could be: app.on("event:terminate", ...

Storing audio files in Firebase Cloud Database and displaying them in React js + Dealing with an infinite loop problem

Lately, I've been encountering a persistent issue that has proven to be quite challenging. Any assistance would be greatly appreciated. Thank you in advance. The objective is to create a form that allows for the easy addition of new documents to the ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Why might a responsive website automatically switch to mobile view?

My website has a responsive grid system that utilizes media queries with breakpoints. However, I am encountering an issue on IE8 where the "mobile version" of the site is being displayed as the default view even when the screen size is set to what should b ...