Tips for maintaining the full width/height ratio of a child image when covering a fixed size container

I have a square container with dimensions of 300x300 and an <img src="" /> image inside.

My goal is for the image to cover the entire container while maintaining its width/height ratio.

  • If the image's width is smaller than its height (portrait), it should have 100% width with some height cropped.
  • If the height is smaller than the width (landscape), it should have 100% height with excess width cropped.

I can easily accommodate images in the container if they are all landscape or all portrait by adjusting the width or height to 100% and setting the other dimension to auto:

.container {
  border: 1px solid black;
  margin: 30px;
  display: inline-block;
  
  width: 300px;
  height: 300px;
  overflow: hidden;
}

img {
  width: 100%;
  height: auto;
}
<div class="container">
  <img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>

<div class="container">
  <img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</div>

However, I am looking for a universal HTML/CSS ONLY solution that will automatically fit the image to cover the container regardless of its orientation.

Note 1: The inner image must not be distorted in any way. It should only fit the container based on the rules mentioned above.

Note 2: I am interested in an approach that does not involve using background-image: url('')

Answer №1

Give this a try

.wrapper {
  border: 1px solid black;
  margin: 30px;
  display: inline-block;
  
  width: 300px;
  height: 300px;
  overflow: hidden;
}

img {
  width: fit-content;
  min-height: 300px;
}
<div class="wrapper">
  <img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>

<div class="wrapper">
  <img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</div>

Answer №2

Following the advice given by Sitaram in the comments section, I implemented the suggested solution and found it to be highly effective.

In addition to ensuring that the images completely cover the square area, they also adapt to the dimensions of the container regardless of its width or height.

Snippet:

.container {
  border: 1px solid black;
  margin: 30px;
  display: inline-block;
  
  width: 300px;
  height: 300px;
  overflow: hidden;
  resize: both;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>

<div class="container">
  <img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</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

Avoid triggering a second event: click versus changing the URL hash

One of the pages on my website has tabs that load dynamic content: HTML <ul> <li><a href="#tab-1">TAB 1</li> <li><a href="#tab-2">TAB 2</li> <li><a href="#tab-3">TAB 3</li> </ul&g ...

How to Use CSS to Perfectly Align Form Elements in the Center of

No matter what I try, I just can't seem to get these form elements centered on the page using CSS. Here is my code snippet: http://jsfiddle.net/VJLst/1/ <style> #divQuizFillBlank { margin-left: auto; margin-right: auto; } #textQuizFill ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

Discovering the indices of undefined array elements in JavaScript without using a loop

Is there a way in JavaScript to retrieve the indexes of undefined array elements without using a loop? Possibly utilizing a combination of map, filter, and indexOf? I have a loop solution that I'm seeking an alternative for - something more concise, ...

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

Different ways to dynamically change tailwind colors during execution

Utilizing tailwind v3, it's feasible to customize existing colors by modifying the tailwind.config file. https://tailwindcss.com/docs/customizing-colors module.exports = { theme: { extend: { colors: { gray: { ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

Creating a video game HUD effect using JavaScript and HTML5

In an attempt to recreate a video game HUD using HTML5, I have styled a div with CSS properties to resemble a game overlay. When a navigation link is clicked, the div should transition from a hidden state (display:none), then flash twice rapidly before fad ...

Foundation: the importance of source order (without using flex grid)

I have a 3-column grid, with content and a sidebar. On small and medium devices each takes up 12 columns. Take a look at the example here: cdpn.io/anon/pen/bqENqG. I am looking to have the sidebar appear after the articles on small and medium devices like ...

Using AngularJS and SpringMVC for uploading multiple files at once

Having recently delved into the world of angularJS, I've been attempting to upload a file using angular JS and Spring MVC. However, despite my efforts, I have not been able to find a solution and keep encountering exceptions in the JS Controller. Bel ...

What are the steps to ensure that the content within the <pre><code></code></pre> tags displays correctly in Internet Explorer 7?

When using JQuery to make an AJAX pull with JSON to an ASP.net Web Service, the following code is used: $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "TestWebService.asmx/Foo", data: "{}", dataType: "json", success: function( ...

Is there any way to remove the two default aspNetHidden Divs in asp.net web forms?

After creating an empty webform page in asp.net, the generated code looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Threetier.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org ...

Can Selenium be used to validate resizing capabilities?

Looking to automate a test case focused on resizing a div element while ensuring that all content in the div remains unchanged, except for its size. Can Selenium help with this task? ...

Mastering the Art of Live Search in Drop Down Multi Select

I need to develop a search functionality similar to the one found on . This search should allow users to select options from a dropdown menu or type their own search query, and provide live search results. I attempted to use the jQuery plugin https://www.j ...

"Exploring the creation of multidimensional arrays in Arduino - what steps should I

Is there a way to create a multidimensional array in Arduino? I want something like this. C++ var arr = { name: "John", age: "51", children: [ "Sara", "Daniel" ] }; or maybe like this. JSON ...

CSS: Adjusting the vertical position of text without affecting the background

I am currently working on some CSS buttons that expand in size when hovered over. I have successfully increased the text size as well, but now I am facing an issue with aligning the text a few pixels lower without affecting the background image layout. Ca ...

Troubleshooting issue with Bootstrap collapse functionality failing with dynamic IDs

Having trouble creating dynamic ids for bootstrap collapsing functionality. I want each topic in an ng-repeat to collapse and display its respective question list when clicked. The issue is that when I click on a second topic, the question list data from ...

Create a new object with the first two keys of the array of objects as keys for the new object, and the third key as an array within that

I am dealing with JSON data from a csv file and need to extract Test and Result values for each object. My goal is to create an indicator array based on the matching Test and Result in each object. [{ "Test": "GGT", "Result ...