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>
https://i.sstatic.net/2luwD.jpg

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

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Is your Navbar having trouble readjusting its height?

My navbar is not resizing properly when I shrink the logo image. Here's a link to the Codepen page with the full code: https://codepen.io/gabor-szekely/pen/JeMqQz I'm trying to reduce the size of the "Sino Medical" logo image in the top left co ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Ways to schedule the execution of a script at a specific time using Node.js

Every time the readDirectory function is called, it checks if any file created date is more than 30 days ago and removes that file from the directory. While this functionality is working correctly, I am concerned about its efficiency. To address this issue ...

Avoid executing top-level path middleware with app.use('/') in Express routing when directly accessing child or nested paths

Perhaps the title may not be as accurate as I hoped, but I have a very simple example to share. On my website, there are two main areas - a public area and a restricted admin area. example.com/admin (admin home page) example.com/admin/news (news page) ...

Paused session in web development

Currently, I am in the process of building a website using HTML and CSS and have encountered an issue. Within my CSS file, I have defined an ID called "full" which sets a wooden background after the sidebar and is intended to span across the entire page. A ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Instructions for activating a button in the absence of any inputs

I need help enabling a button in angularjs based on whether any of the inputs are filled out. I was successful in disabling a button when only one input is checked, but how can I do this for all inputs affecting one button? This is what I've attempted ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

What are some techniques for reducing the number of pages in my Carousel?

I need help figuring out how to set a limit of noOfPages for the number of pages per carousel. The functions in my code below don't implement this and I'm unsure how to do it. const itemsPerPage = 6; const [page, setPage] = React.useState(1); ...

Challenges faced when attempting to launch a React-powered application on Railway platform

When I transferred my fullstack app (React + Express) from Heroku, I encountered an issue. React apps need to be built to run and require necessary dependencies installed, but typically only raw source code is stored on Git. A typical structure for fullst ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

Creating a customizable navigation bar using only CSS

I'm currently working on creating a navigation bar using only HTML and CSS, without the need for JavaScript to open and close it. However, I've encountered an issue where the navigation bar remains open even after setting display: none or visibi ...

Exploring Rails 6: Enhancing Web Design with CSS Image Display

I've been attempting to update my webpage background with an image through CSS, but I'm struggling to reference one of my Rails 6 images in the process. Despite trying options like asset-url and image-url, I haven't been successful. However, ...

Tips on connecting a file upload button to a flip card

In my current project located in index.html, I have integrated a flip card as a profile photo feature. Additionally, I have included a file uploader button on the page. However, I am struggling to connect the functionality of the file uploader button to au ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...

What is the most effective way to eliminate asynchronicity in a function?

Imagine having this block of code: const myFunction = async => { const result = await foobar() } const foobar = async () => { const result = {} result.foo = await foo() result.bar = await bar() return result } Now, let's transform i ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: If anyone has ...

Transforming multi-layered form data into a JSON array structure for seamless integration with application/json

I'm currently developing a Laravel application and facing an issue with the $controller->wantsJson() method in the back-end. This method returns TRUE only if the content type of the request is set to application/json. jQuery.ajax({ type: ...