Adjust the size of an image based on the smaller dimension utilizing CSS

Allowing users to upload images that are displayed in a square container in the UI presents challenges. The uploaded images can vary in size, aspect ratio, and orientation, but they should always fill the container and be centered.

To address this issue, I aim to style the images so that the smaller dimension is set to a specified size while maintaining the original aspect ratio.

If I want all images to have a resulting dimension of 50px (for the smaller side), the conversions would be as follows:

  • Portrait image: 100px(w) x 200px(h) => result: 50x100
  • Landscape image: 200px(w) x 100px(h) => result: 100x50
  • Square image: 100px(w) x 100px(h) => result: 50x50

I require the images to be at least 50px in either dimension. By using max-width and max-height properties, the images will resize to at most 50px...

Criteria for the original approach

  1. CSS only should be used
  2. The images must be IMG tags and should not be placed as backgrounds
  3. Avoid using Javascript

While experimenting with max-dimension styles, I found that controlling both dimensions simultaneously was challenging. I am seeking a solution that addresses this limitation.

Considerations for an alternative approach

The requirements of the original solution may prove too restrictive. In such cases, utilizing CSS backgrounds as outlined in this question could be considered. However, my challenge lies in dynamically defining the images at runtime when users select them, requiring inline styles which I prefer to avoid.

Answer №1

Solution Implemented

Regrettably, it is not feasible to adjust the size of images directly using only CSS. Specifically, this limitation applies to the IMG elements. However, the feature is supported for background images of elements. Given that IMG elements are no exception in this scenario, backgrounds can be set on them as well. I chose to display a transparent image and apply a background to achieve the desired effect.

Here is the approach I adopted:

img {
    height: 50px;
    width: 50px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

I am utilizing inline CSS to programmatically define the background image. The images are fetched from the local file system using FileAPI, and I am incorporating data URIs to set them as backgrounds.

Success achieved...

Answer №2

Check out this CSS code for styling image tags:

img{
 max-width: 100px;
 max-height: 100px;
}

With this code, you can achieve both Portrait and Landscape images while maintaining their aspect ratio. Only Square images will be constrained to 100x100 dimensions. Here is a fiddle link for reference.

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

Extracting information from CSS code

I am struggling to parse a RSS feed because all the information is contained within the description element. The CSS formatting makes it challenging to extract the actual strings. For example, below is a snippet of the description element: <table style ...

What is the best way to create a line break in a flex div container to ensure that overflowing items wrap onto the next line using

Using material-ui popper to display a list of avatars. Trying to arrange the avatars horizontally within the popper. <Popper style={{ display: 'flex', maxWidth: '200px', }}> <div style={{ marginRight: '20px' }}&g ...

How to target the following sibling element (not a child) with CSS

I am working with the following HTML structure: <div class="col-sm-12"> <input id="my_id"> <div class="col-sm-1 col-3-box" style="position:absolute; margin-left:340px;"> </div> </div> How can I target and change ...

Change the size of the image to use as a background

I have an image that is 2000x2000 pixels in size. I originally believed that more pixels equated to better quality with less loss. Now, I am looking to display it on my browser at a resolution of 500x500. To achieve this, I attempted to set the image as t ...

How to Use CSS to Align an Image in a Header

I'm struggling to position an image on the top right corner of my page, specifically in the header. Despite searching for help on Stack Overflow and other online resources, I can't seem to figure it out. Currently, here is what I have: The seco ...

Problem with see-through images against a see-through backdrop

I'm experiencing a strange issue with a graphic that has rounded corners. On my HTML page, I have the body set to transparent (style="filter:alpha(opacity=100);opacity:100;background-color:transparent;"), and within this body is a div containing a PN ...

What is the method for using jQuery to retrieve hidden fields with the visible attribute set to "false"?

How can I access a control with "visible = false" attribute using jQuery? Some code examples would be appreciated. <tr>   <td class="TDCaption" style="text-align: left">     <asp:Label ID="lblMsg" runat="server" EnableViewState="False" F ...

The particles.js with absolute positioning is currently overlapping my div with relative positioning

Visit this link <div class="outer-container"> <div id="particles-js"> <div class="your-content"> <article id="3" class="bg-dusk transition md:group-hover:opacity-50 md:hover:opacity-important md:hov ...

Using CSS to add color to the border of a shape

Is there a way to make only the top, shaped part of this polygon have a 2px blue outline? .graph { clip-path:polygon(0 78%, 9% 67%, 32% 77%, 56% 60%, 69% 30%, 88% 40%, 100% 20%, 100% 100%,0 100%); border:none; height:200px; width:100%; ...

Django - issue with table display showing empty row due to query set

In my project, I have two models: one named Season and the other one named Game: # Season class Season(models.Model): teams = models.ManyToManyField('Team', related_name='season_teams', blank=True) current = models.BooleanF ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

How can we use a :before tag element to create a hovering effect on an image that remains clickable?

My objective is to create an image that is wrapped in a link. The link will have a pseudo element :before that adds a black overlay on hover. I want the image to remain clickable, but no matter what I try, the pseudo element won't position correctly o ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

What is the best way to adjust the height of the second column downwards?

I am trying to achieve a 2-column layout with both columns at the same height. This is how it currently appears: And this is how I want it to be: Here is my code snippet: html { background-color: lightblue; font-family: Tahoma, Geneva, sans-serif ...

text breaks free from the flex container when zooming in

Hi, I am attempting to design a user card-type div that includes images on the left and the username on the right. I have managed to create the layout, but when zooming in, the text is overflowing and escaping the flex container. Here is my code snippet. Y ...

Using animation in CSS is limited to only one time

My goal is to create a pulse animation that triggers when a button is clicked. This image shows the animation midway: https://i.stack.imgur.com/EHDqs.png When the button is clicked, the animation plays once and then stops. However, I want the animation to ...

Switching up the Label Colors in Chart.JS

It's been a while since my last question, so please bear with me if I'm not following the rules. I've attached my current code and a reference image of the chart. I am completely new to working with ChartJS. The situation is a bit unique: t ...

How can I add a drop-down list to a cell within a table?

Can a drop-down list be added into a table cell? Thank you! Here is an excerpt of the code: $sql_query="SELECT nameOfwarning FROM warnings"; $sodss=mysqli_query($d,$sql_query); if (mysqli_num_rows($result)<1) ?> <select name = "warnings"> ...

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...