Adjusting the image to fit the container based on its shorter side, regardless of the image's orientation

I have a square container with a predetermined size. I want to place an image inside the container so that its smaller side fits perfectly with the parent container, while the larger side extends beyond the edges of the container without distorting the image. Essentially, the smaller side should be exactly 100% of the container, but both sides should be greater than or equal to 100%. This must be achieved without altering the proportions of the image.

This solution should work regardless of whether the image is in landscape or portrait orientation, as I want it to cover both cases without needing to know the image's orientation in advance.

Would setting the min-width and min-height of the image to match the height and width of the parent container be a viable solution? Or perhaps someone has another simple method to achieve this?

Any suggestions would be greatly appreciated. Thank you, Sebastian

Answer №1

By utilizing CSS alone, it is feasible, although cross-browser support may be lacking. Hello, Internet Explorer:

img {
  object-fit: cover;
  max-width: 100%;
  max-height: 100%;
  min-width: 100%;
  min-height: 100%;
}

Witness it in action:

.sized-container {
  width: 25vw;
  height: 25vw;
  display: inline-block;
  float: left;
}
.sized-container img {
  object-fit: cover;
  max-width: 100%;
  max-height: 100%;
  min-width: 100%;
  min-height: 100%;
}
body {margin :0;}
<div class="sized-container">
  <img src="https://loremflickr.com/640/360">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/360/640">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/100/100">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/1000/1000">
</div>


To achieve a solution compatible across all browsers, JavaScript has to come into play.
Hide the <img> elements while extracting their src values to set as container backgrounds. These containers have background-size:cover to deliver precise sizing and cropping behavior as needed.
This solution also enlarges small images to adapt to the width/height of their parent containers:

let containers = document.querySelectorAll('.sized-container');
for (let i = 0; i < containers.length; i++) {
  var container = containers[i],
      image = container.querySelector('img');
  if (image)
    container.style.backgroundImage = 'url(' + image.getAttribute('src') + ')'
}
.sized-container {
  width: 25vw;
  height: 25vw;
  background: transparent 50% 50% no-repeat /cover;
  float: left;
}
.sized-container img {
  display: block;
  width: 100%;
  height: 100%;
  opacity: 0;
}
body { margin: 0;}
<div class="sized-container">
  <img src="https://loremflickr.com/640/360">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/360/640">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/100/100">
</div>
<div class="sized-container">
  <img src="https://loremflickr.com/1000/1000">
</div>

If jQuery is used, the script can be more concise:

$('.sized-container').each((i,e) => {
  let img = $('img', e);
  if (img.is('img'))
    $(e).css({backgroundImage:'url(' + img.first().attr('src') + ')'});
})

Note: Ideally, when generating the markup, setting the background-image of the parent should be considered to avoid fetching it from images using JavaScript. Nevertheless, for accessibility purposes (such as screen readers, title attributes, etc.), keeping the <img> elements hidden is recommended.

Answer №2

One way to approach the issue is by setting the image as a background image. However, keep in mind that the behavior may differ from using the <img> tag.

To achieve this effect, you can apply the following CSS on a <div> element or a similar container:

height: [HEIGHT] px;
width: [WIDTH] px;
background-image: url('[URL]');
background-size: cover;

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 it possible to scroll the grid horizontally?

I have a grid that scrolls vertically, with columns adjusting their width automatically. .grid { display: grid; overflow-y: auto; grid-template-columns: repeat(auto-fit, minmax($min-column-width, 1fr)); } Now, I'm attempting to create a horizon ...

The concept of setting a value is not defined in JavaScript when compared to

Within my primary python script, the following code snippet is present. @app.route('/accounts/test/learn/medium') def medium(): word = random.choice(os.listdir("characters/")) return render_template('accounts/test/medium.html', word=w ...

Merge different $_GET parameters together before submitting

Not too certain if it's achievable, but here's the issue I'm struggling with. I need a form that generates this specific link. The desired end link is: I am unable to utilize a form for this task, but I can work with input fields. Any sug ...

Struggling to eliminate margins in a React web application

Can anyone assist me with removing the large white margins on my react project? Here are some solutions I have attempted. * { margin: 0; padding: 0; } /-/-/-/ body { max-width: 2040px; margin: 0 auto; padding: 0 5%; clear: both; } I've exp ...

The issue of overflowing scroll functionality appears to be malfunctioning

.main-content{ height: 100%; width: 60%; min-height: 800px; background-color: white; border-radius: 5px; margin-left: 1%; border: solid 1px black; } .profile-banner{ display: flex; flex-direction: row; justify-content: space-between; ...

Using simpleXML to extract HTML code from an XML document

Presented below is content extracted from an xml file: <Cell> <Comment ss:Author="Mark Baker"> <ss:Data xmlns="http://www.w3.org/TR/REC-html40"><B><Font html:Face="Tahoma" html:Size="8" html:Color="#000000">Mark B ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...

Extracting URLs using Selenium from specific cells within a table

While parsing a webpage table, I noticed that one of the columns contains a hyperlink. The structure of the table is as follows: <table id="GridView1"> <tbody> <tr> ... </tr> <tr> ...

Aligning a div vertically in the center of its parent container

I am trying to vertically align a child element within its parent element <!DOCTYPE html> <html> <head> <title>Test</title> <style type="text/css"> #body { font-family: sans-serif, arial, 'Roboto'; } #outer ...

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Converting an HTML table into a visual image

I've encountered an issue. My task involves transferring an HTML table to a PDF using fpdf. Is there a way to transform an HTML table into an image (via URL link)? ...

having difficulty choosing a single radio button at once

I'm having trouble selecting just one radio button at a time. Instead, multiple buttons are being selected. I'm new to HTML and this is the code I'm using. Can someone please assist me with this issue? <form name="ans_a" onsubmit="return ...

Align a series of divs in the center with variable width and height

I have a dilemma with my large div that contains multiple thumbnails. I am looking to center the thumbnails within the div and have the overall div centered on the page. Additionally, I want the width of the div to be flexible so that all thumbnails can be ...

Creating an HTML button that functions as a link to a specific section on the same page

I am interested in creating an HTML button that functions as a link to an item on the same page. Essentially, when this button is clicked, it should redirect to an item within the same page. Is there a way to achieve this using only HTML, CSS, and JavaScr ...

What is the best way to prevent the navbar from covering content? The navbar-static-top option helps, but it doesn't allow for fixed-scroll

I am facing an issue with my navigation bar while using asp.net. When I apply the class navbar-fixed-top, the navigation bar becomes fixed and scrolls with the page, but it overlaps the content in the contentplaceholder However, when I switch to the clas ...

Choosing comparable choices from the drop-down menu

I am working on a dropdown menu that contains different options. I need to use jQuery to automatically select the option that corresponds to the branch of the currently logged in user. However, when some option text is very similar, it causes an issue. // ...

Using jQuery to generate nested lists

I have attempted various solutions for creating nested ul/li elements without success. I am a beginner in JavaScript and struggling with this task. The data is retrieved after the page has loaded, and it looks like this: data = { "key1": ["value1", va ...

Begin by opening a single div for each instance

I want a functionality where opening one div closes all the others. I've searched around for solutions and only found jQuery options, not pure JavaScript ones. Here is my code: function openDescription(description_id) { var x = document.getEle ...

Guiding you to choose a specific child class by identifying its parent class in CSS and jQuery

Hey there! I'm currently working on a website that allows users to post content. I want to ensure that the site is mobile-friendly, so I need to make some adjustments with media queries. Unfortunately, I've run into an issue where media query CS ...