The width of a flex item will always match the intrinsic width of the image content

Objective

  1. I aim to place an image within a child div that is a flex item in a parent flex container.
  2. The goal is for the image's height to be equal to the height of its containing div while still maintaining its aspect ratio.

My understanding

  1. Setting the image's height to 100% should adjust its size to match the child div's height while preserving its aspect ratio. (this behaves as expected)
  2. However, the width of the child div does not adjust accordingly and ends up matching the original width of the unscaled image. (this is not the desired outcome)

Issue

The width of the child div matches the intrinsic width of the image rather than adapting to the scaled-down image's new width, resulting in extra space on the right side of the child div.

<html>
   <head>
      <style>
         .parent {
             display: flex;
             width: 1000px;
             height: 400px;
             padding: 10px 0px;
             background-color: red;
         }
         .child {
             padding: 10px 0px;
             background-color: blue;
         }
         .child > img {
             height: 100%;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div class="child">
            <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
         </div>
      </div>
   </body>
</html>

Answer №1

It seems like a simple solution, but I was able to resolve this issue by including height: 100%; in both the .child and .child > img classes. Here is the updated code:

<html>
   <head>
      <style>
         .parent {
             display: flex;
             width: 1000px;
             height: 400px;
             padding: 10px 0px;
             background-color: red;
         }
         .child {
             height: 100%;
             background-color: blue;
         }
         .child > img {
             height: 100%;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div class="child">
            <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
         </div>
      </div>
   </body>
</html>

Answer №2

 .container {
             display: flex;
             width: 1000px;
             height: 400px;
             padding: 10px 0px;
             background-color: red;
         }
         .content {
             padding: 10px 0px;
             background-color: blue;
         }
         .content > img {
            height: 100%;
            width: 100%;
            object-fit: cover;
         }
<html>
   <body>
      <div class="container">
         <div class="content">
            <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some image">
         </div>
      </div>
   </body>
</html>

Answer №3

To ensure the image takes up the entire space of the div, set its width to 100% and maintain its aspect ratio with object-fit: cover;. Check out this live example here: https://codepen.io/maha986/pen/BaWqrGb

If you need to reduce the size of the child div, simply adjust its width as needed.

You can style your child div and image like so:


.child {
padding: 10px 0px;
width: 500px;
background-color: blue;
}

.child > img {
height: 100%;
width: 100%;
}

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

How can objects be positioned or moved in a linear fashion, and how to incorporate free fall when adding additional objects?

I'm interested in creating a system similar to a "vibrating table" with linear displacement. After studying various tutorials, I was able to achieve simulations based on the following examples: Following the tutorial "Authoring a Multibody Simulatio ...

Creating an HTML form that spans across multiple pages: Tips and tricks

When creating a shopping form that includes items like mugs and tshirts, is it permissible according to website standards to design a form that spans multiple pages? One option could be to add radio buttons for choosing a color directly on the main form ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Dynamic Content Sorting with JavaScript and jQuery

I am presenting various courses that are available, and I am utilizing JavaScript/jQuery to display or hide them based on element classes. You can view the page here. Currently, the script conceals all content on the page and then reveals items that matc ...

A complete div component with a minimum height that is sandwiched between a fixed size header and

I'm currently facing a challenge with setting up my webpage due to the height of my elements causing a bit of a frenzy. Specifically, I have a specific layout in mind: At the top, there should be a header that has a fixed height (let's say 150p ...

Retrieve the text of the chosen option, rather than the value

Having a multiple select, my goal is to retrieve the selected text rather than the value. For example, if I have this: <option value="1100"> MH-03-P-9429</option> I want to extract MH-03-P-9429 as the selected text. However, when I use $(" ...

Adding a directive to create a table header

I'm having trouble with an angular directive that is meant to insert a table header. Unfortunately, instead of being placed inside the thead as intended, it ends up outside of the table element. Here's a link to the codepen: http://codepen.io/sac ...

Update the color scheme according to a specified custom value

I am currently utilizing the Metronic theme for my Angular application and I have a unique requirement. I would like to allow users to personalize their own color scheme within the application. However, I am facing challenges in understanding how to dyna ...

`Why won't my xpath expression function properly?`

<DOC NUMBER=1> <DOCFULL> --> <br><div class="c0"> <p class="c1"><span class="c2">Document 1 of 3</span></p> </div> <br><div class="c0"> <br><p class="c1"><span class="c2"&g ...

Can we dynamically adjust font size based on the width of a div using CSS?

My div is set to 70% width and I have a specific goal in mind: To fill that div with text To adjust the font size so that it takes up the entire width of the div https://i.stack.imgur.com/goVuj.png Would it be possible to achieve this using only CSS? B ...

Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-tex ...

When I try to collapse the element at the bottom of my page, it fails to anchor to the newly opened element after clicking

I have a situation where an element at the bottom of my HTML page is not collapsed by default. When I click on an arrow just above it, the element displays. However, since the newly collapsed element is still "below the fold", users have no clue that click ...

CSS vertical alignment property

I'm facing a rather simple problem that has left me scratching my head. The vertical align property is performing correctly, but as soon as I introduce a tag after the text meant to be centered along the image, any text that follows the tag appe ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

Error encountered: Local HTML file - XMLRequest: Access denied due to network error 0x80070005

Update: My issue is not a duplicate, as it persists across all browsers such as Edge, Chrome, and Firefox. I am working with an HTML file that will reside on the user's local machine, rather than being accessed through an HTTP protocol. It is crucial ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

The php code managed to infect my website

My website has been infected by a plugin that is generating ads for a company I am not affiliated with. I tried using anti-malware software, but it didn't detect anything. var doc = document.getElementById('ad_iframe').contentWindow.document ...

What steps can be followed to create functionality for having three pop-up boxes appear from just one?

I have implemented code that triggers pop-up boxes at the bottom of the screen when a user clicks on a name from a list displayed on the top right corner of the screen. <!doctype html> <html> <head> <title>Facebook Style Popu ...

Is it possible to incorporate an AngularJS variable within internal CSS?

Currently I am working on an AngularJS project and I have a requirement to use a dynamic color defined by the user in CSS. Is there a way to implement this dynamic color in my CSS using AngularJS, vanilla JS, or SASS? For example... Internal CSS in HTML ...

Ways to reference a PHP variable within an anchor tag

I've been working on a page that pulls data from a MySQL database into a table. My goal is to allow users to click on the date in the table and be redirected to another page. Here's the code snippet I'm currently working with: $q = "SELECT ...