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

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

Tips for keeping the scroll position of a bootstrap table when reloading the page

Displayed below is a bootstrap table with specific features. <div class="row"> <table id="question-selection" class="table table-sm table-hover table-wrapper"> <tbody> {% for placer in chapter_questions %} ...

"Troubleshooting: Click counter in HTML/Javascript unable to function

My latest HTML project is inspired by the "cookie clicker" game, and I'm working on it for a friend. So far, I've managed to get the click counter to function to some extent. Essentially, when you click on the image, the number at the bottom sho ...

issues with background image alignment in css

I attempted to add a sticky background to a div, which was successful. However, I am encountering an issue where the background does not stretch enough during scrolling. Below is the CSS code I used to apply the background, along with screenshots displayin ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

I possess a table that showcases MatIcon buttons. Upon clicking on a button, two additional buttons should appear at the bottom of the table

I am working on a table that contains mat-icon-buttons. When the button is clicked, it should display 2 additional buttons at the end of the table. Upon clicking the first button, its color changes from primary to red, and I would like to add two more butt ...

When adding text to a React Material UI Box, it can sometimes extend beyond the boundaries

I'm currently working on a straightforward React page, but I've encountered an issue right from the start: my text is overflowing the box and I can't figure out why. Could someone take a look at my styles? Here's a picture showing the ...

Creating a "select all" feature in an HTML multiple select box with jQuery - a step-by-step guide

I'm currently working on an HTML form that includes a multiple select box. I am looking to create a "select all" option within the multiple select box so that when a user clicks on that option, all other options in the select box are automatically sel ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

Applying box shadow to input group addon in Bootstrap 3 using CSS

What I am trying to achieve is that when I click on the inputbox or selectbox, the box shadow defined in my CSS should also cover the input-group-add-on feature in Bootstrap 3. The issue I'm facing is that the input-group-add-on does not display the ...

Trying to conceal the scrollbar on MS Edge and Firefox?

Currently, I am working on a scrollable menu that requires the scrollbar to be hidden. In Chrome, I have achieved this by using the following code: .menu::-webkit-scrollbar { display: none; } I would like to know if there is an equivalent solution ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Place elements in a grid layout using CSS (and also ensure they are centered)

My goal is to create a data-grid (table layout) where the elements have fixed sizes. These elements should be placed in the same line until they can't fit anymore, then move to the next line. I have tried using inline-blocks for this, but I'm st ...

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

Encountering issue with Django locating static file (1.5) showing ERROR 404 code 1649

I'm facing some difficulties in setting up my local Django site. I've reviewed the previous questions and answers, but haven't been able to find a solution. [20/Oct/2013 03:56:33] "GET /rides/ HTTP/1.1" 200 230 [20/Oct/2013 03:56:33] "GET / ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

tips for reducing the size of the recaptcha image to display just one word

The custom recaptcha theme I'm working with requires the image to be smaller in width but not in height. Is there a way to achieve this requested design? ...

How can I receive user input in JavaScript while incorporating three.js?

I am currently exploring the functionalities of this three.js example () and I am interested in enabling users to input specified X, Y, and Z positions for boxes dynamically. Initially, I considered utilizing a JavaScript prompt like below: var boxes = p ...

Using CSS3 gradient in grey instead of white

I came across an amazing example by Chris Coyier showcasing a "read more" button. I attempted to replicate this by creating a simple fadeout effect from white to transparent, but unfortunately, I ended up with a grey gradient instead. You can view my atte ...