The CSS property object-fit: contain; ensures that the original image width is maintained in the layout

I am attempting to create responsive images within flexbox containers using the CSS property object-fit: contain. While the images are resizing, the layout seems to be maintaining the original size of the image, resulting in a scrollbar appearing.

Upon inspecting the width of the image in Chrome Dev Tools, I noticed that the width remains at 1024 (although the height is appropriately reduced).

(I found inspiration from Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio? up to this point)

Is there something missing in terms of additional CSS attributes?

JSFiddle Link: https://jsfiddle.net/w6hgqf18/1/

https://i.sstatic.net/qIZJO.png

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
}

.page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

.page-footer {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

img {
  object-fit: contain;
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</div>

Answer №1

If you understand the logic behind it, using the object-fit property is quite simple. Let's break it down with an example:

.box {
  width:300px;
  height:300px;
  border:1px solid;
}
img {
 width:100%;
 height:100%;
 object-fit:contain;
}
<div class="box">
  <img src="https://picsum.photos/300/200?image=1069">
</div>

In this example, I've used a 300x200 image inside a 300x300 box, which stretches and breaks its original ratio. However, even after applying object-fit, the image dimensions remain 300x300.

According to the specification:

The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

In simpler terms, visually we adjust the content of the image to fit within the space defined by the image itself.

Extending the same example with 50%:

.box {
  width:300px;
  height:300px;
  border:1px solid;
}
img {
 width:50%;
 height:50%;
 object-fit:contain;
}
<div class="box">
  <img src="https://picsum.photos/300/200?image=1069">
</div>

Now, the image size becomes 150x150 where the content maintains the contain effect.

This concept applies to all values of object-fit.

Considering your scenario without object-fit, the image behaves differently as shown below:

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
}

.page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

.page-footer {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

img {
  /*object-fit: contain;*/
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</div>

Introducing object-fit does not alter the image size but only affects what is visible:

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
}

.page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

page-footer {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

img {
  object-fit: contain;
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</div>

The issue you are facing with the image having a width of 1024px relates to the flex items not stretching beyond their content size due to the min-width constraint. To resolve this, include min-width:0 to achieve the desired effect, containing the image within the flexbox layout area.

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  min-width: 0; /*added*/
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
}

.page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

.page-footer {
  flex: 0 0 auto;
  page-background-color: #dcdcdc;
}

img {
  object-fit: contain;
  min-width: 0; /*added*/
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="half-containers">
      <img src='https://i.imgur.com/tqQvuFr.jpg' />
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</div>

Another approach could be utilizing background-image along with background-size:contain, removing the need for min-width constraints since there's no actual content involved:

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
  background:url(https://i.imgur.com/tqQvuFr.jpg) center/contain no-repeat;
}

page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

page-footer {
  flex: 0 0 auto;
  background-color: dcdcdc;
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
    </div>
    <div class="half-containers">
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</div>

Answer №2

To achieve the desired effect of wrapping an img tag with a div element without using object-fit, you can set the image's width to 100% and its height to 100%. Here's how you can do it:

html,
body {
  margin: 0;
  height: 100%;
}

.page {
  height: 100%;
  display: flex;
}

.main-container {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}

.half-containers {
  flex: 0 1 50%;
  overflow: auto;
  box-sizing: border-box;
  border: 0.5px solid red;
  display: flex;
}

.page-header {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}

.page-footer {
  flex: 0 0 auto;
  background-color: #dcdcdc;
}


.img-container {
  width: 100%;
}

img {
  height: 100%;
}
<div class="page">
  <div class="main-container">
    <div class="page-header">
      This is a header
    </div>
    <div class="half-containers">
      <div class="img-container">
        <img src='https://i.imgur.com/tqQvuFr.jpg' />
      </div>
    </div>
    <div class="half-containers">
      <div class="img-container">
        <img src='https://i.imgur.com/tqQvuFr.jpg' />
       </div>
    </div>
    <div class="page-footer">
      This is a footer
    </div>
  </div>
</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

Setting the z-index for Bootstrap dropdown menus on containers that are generated dynamically

When using the Bootstrap 3 dropdown-menu within a dynamically generated container, I am encountering an issue where the dropdown-menu appears behind the newly created elements. Please refer to the image for visual clarification. The container item has pos ...

Superimpose above the tbody

I am attempting to implement a loading overlay specifically on top of the tbody element. My current method involves adding a tr as the last child of tbody and positioning it using position: absolute, while setting the parent tbody with position: relative. ...

I am in need of help with coding so that my entire webpage is displayed properly even when I resize it to the smallest width. Additionally, I need assistance with making

Having some issues with making my personal website work correctly. I'm planning to share images of how it looks at different widths - largest width and smallest width. Also, here are the links to my website here and to my GitHub code here Seeking gui ...

What is the best way to hide a dynamically generated class using CSS display property?

Is there a way to hide a dynamically generated class in a table row? I am trying to figure out how to hide this dynamic class that appears on the table row. In other words, I need to hide a row in the table that includes this dynamic class. Even when I add ...

Ways to restrict access to resources

My static website is simple, but I am concerned that everyone has access to my assets. For example, when I go to www.mysite.com/assets in the browser, it shows: Index of /assets Parent Directory css/ img/ js/ Is there a way to display a 403 error page ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

Content in Tab Fails to Load due to IFRAME URL

On my web page, I have embedded an IFRAME with its src attribute set to load HTTPS content. This IFRAME is placed within a Bootstrap Nav-Tab Content, which in turn is located inside a Card element. Upon loading the webpage, I noticed that the content does ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...

Ways to showcase the row count in SQL query using COUNT

Upon executing the query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin, it accurately retrieves the total number of rows within my database. To further enhance this functionality, I now seek to showcase this figure on my success.php page utilizing the cou ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

Inclusions of embedded Google Docs in iframes

I recently posted a Google Document with some helpful links. To display it on my webpage, I utilized an iframe code. However, whenever someone clicks on one of the links within the document, the iframe is replaced by the target URL of that link. In order ...

SQL AJAX-driven cascading dropdown menu

I have a database consisting of 5 tables, each representing a subcategory of the previous one: countries states cities ZIPcode streets Currently, I have 3 dropdowns that are interdependent. For example, selecting countries: USA will show only the states ...

Using JavaScript to launch link in a new pop-up browser tab

Currently, I am customizing a WordPress theme and trying to add inline sharing buttons at the end of posts. However, I have encountered a roadblock in my progress. My goal is to have the link open in a new popup window using JavaScript. Below is the HTML c ...

Enhance your Forumotion profile with customizations using jQuery that are tailored to the

My concept involves utilizing a jQuery snippet (I prefer JQuery over regular javascript due to my comfort level with it) that is able to identify when it is executed on a profile page with a specific URL format like "" (just for demonstration purposes). On ...

Generating a fresh row while utilizing ng-repeat in AngularJS

I have implemented a basic ng-repeat function to create a list of countries along with their relevant data. Each entry in the list contains a hidden row that can be expanded or collapsed. I am facing an issue where I cannot get the hidden row to display c ...

Creating unique URLs for websites can be accomplished by following these steps:

I am in the process of developing a website where content in the main div within the body section can be replaced. However, I have realized that all content will end up on the same URL. Any suggestions on how to fix this? HTML/PHP(index.php): <htm ...

Unable to rotate 3D cube

Struggling with getting my cube to rotate properly while coding. Anyone able to assist? I've exhausted all options. See my code here: Link to Codepen @keyframes spin { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } } bo ...

Seeking guidance on selecting text using XPath

My HTML document contains the following HTML code: <!DOCTYPE html> <html> <head> <title>page XYZ</title> </head> <body> <p><b>bold text</b> some more text </p> <p>< ...

Ways to retrieve anchor tag values from an AJAX response without a defined class

if(ajaxRequest.readyState == 4) { var response = ajaxRequest.responseText; response=response.split('^^--^^'); var buname=response[5].split('^^|||^^'); //rest code } The AJAX request has returned the following code, now stored in the va ...

What is the best way to center a CSS box on the screen?

I am attempting to center the login box on the screen, but when using position: absolute the background color changes to white. /* all */ .patua_font { font-family: 'Patua One', cursive; } .Roboto_font { font-family: 'Roboto&apo ...