What arrangement works best for combining flexbox with images?

I'm finding it challenging to grasp the various image size settings in Flexbox. It seems like every time I try to apply them, I end up with a different outcome.

Instead of just saying "it depends on the situation," can someone provide a logical explanation that connects these different scenarios? I want to understand why the results vary each time, particularly in terms of image placement based on viewport size. Let's assume I am using object-fit: cover for all cases. Here's an example featuring two images side by side.

index.html

<section>
        <figure>
                <img src="profile image1.jpg" alt="">

        </figure>
        <figure>
                <img src="profile image2.jpg" alt="">
        </figure>
</section>

style.css

section {
  display: flex;
}

Scenario 1

style.css

/* set the figure wrapper's dimensions only */
figure {
  flex: 50%;
  width: 100%;
  height: auto;
}

Scenario 2

style.css

/* set both the figure wrapper and image dimensions as percentages */
figure {
  flex: 50%;
  width: 100%;
  height: auto;
}

img {
  width: 100%;
  height: 100%;
}

Scenario 3

style.css

/* set both the figure wrapper and image dimensions in pixels */
figure {
  flex: 50%;
  width: 400px;
  height: 400px;
}

img {
  width: 400px;
  height: 400px;
}

Scenario 4

style.css

/* set the figure's dimensions with max-width and max-height */
figure {
  flex: 50%;
  max-width: 400px;
  max-height: 400px;
}

img {
  width: 100%;
  height: 100%;
}

Scenario 5

style.css

/* set both the figure and image dimensions with max-width and max-height */
figure {
  flex: 50%;
  max-width: 400px;
  max-height: 400px;
}

img {
  max-width: 100%;
  max-height: 100%;
}

I am trying to understand the advantages of placing the image within a container with varying configurations of pixel or percentage dimension units.

Answer №1

  • When the image width is not set (scenario #1), it will default to its original dimensions, potentially causing it to overflow the page. This behavior disregards any wrapper configuration.

  • Setting the img width to 100% forces it to fit within its container, triggering flex configurations to take effect.

  • In scenario #2, setting the flex item's width to 100% may result in shrinking unless explicitly prevented with flex-shrink: 0.

  • According to Flexbox specifications, when flex-wrap is nowrap, items are assigned equal width by default. With two figures in a section, each figure may end up occupying 50% of the container width.

  • The outcome is that the images will resize to fill their respective containers, appearing side by side.

  • Specifying a fixed width for the figure element as a flex item may be overridden by browser calculations based on flex-grow and flex-shrink. Allowing flexible resizing can keep items in a single line layout.

  • In scenario #3, where flex-basis is set at 50%, the specified width may be ignored in favor of fitting elements next to each other while ensuring image tags conform to container width.

  • Scenarios #4 and #5 involve setting max-width for figure items, which overrides calculated widths. If the calculated width exceeds the max-width, the final width will adjust accordingly.

Answer №2

  • Scenario 1
    • The images are displayed at their natural size. If they are smaller than the flexboxes, they align to the left or their respective flexbox like text, creating two columns. However, if they are larger, they will overflow. It is not recommended due to potential overflow issues.
    • flex: 50% is a shorthand for
      flex-basis: 50%; flex-grow: 1; flex-shrink: 1
      . The figures have both a flex-basis and a width, but only the flex-basis is considered. This means that the algorithm first creates the figures at 50% of the width of their parent, then either grows or shrinks them evenly to fit the parent. Regardless, the images will likely overflow if they are too large.
  • Scenario 2
    • Similar to Scenario 1, setting width: 100% on the figure is unnecessary.
    • If you give the images both a height and width, they will stretch to fill their parent. It is advisable to only set width, allowing the height of the image to adjust automatically while respecting the aspect ratio.
  • Scenario 3
    • The specified width and height of 400px on the figure are ignored because flex: 50% sets the flex-basis as a priority.
    • The image is stretched to be exactly 400px by 400px, which could result in horizontal overflow.
  • Scenario 4
    • The figures are constrained from growing beyond 400px width, so if 50% of their parent exceeds that limit, they will remain at 400px wide. With no defined height and children having relative height of 100%, their height is capped at 400px. Further insights on this behavior are welcome in the comments section.
    • The images are stretched to completely fill the flexbox, losing their original aspect ratio in the process.
  • Scenario 5
    • The figures behave similarly to scenario 4.
    • The images maintain their original size unless they are wider than the parent figures, in which case they are resized down. Setting both max-width and max-height may lead to distortion of the original aspect ratio during resizing.

Additional Recommendation

To avoid unnecessary growth of figures, especially when styling and adding legends to images, consider the following example:

section {
  display: flex;
}
figure {
  background-color: #dca;
  padding: 20px;
}
img {
  max-width: 100%;
}
<!-- PS: the width and height attributes on img tags emulate actual image size -->
<section>
  <figure>
    <img width="200" height="100" alt="">
    <legend>Fig. 1</legend>
  </figure>
  <figure>
    <img width="400" height="100" alt="">
    <legend>Fig. 2</legend>
  </figure>
</section>

The default flex-styles for any element are:

flex-grow: 0;      /* do not grow */
flex-shrink: 1;    /* shrink automatically to fit parent */
flex-basis: auto;  /* determine size based on content */

In cases where neat column fitting is required, applying flex: 50% to a wrapper around the figure elements might prove beneficial. Adding background colors to elements during testing can also aid in understanding layout behaviors.

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

Overrides of variables are not always complete

After setting up my project with npm install to utilize sass overrides, I encountered an issue. Despite adjusting the $theme-colors, only part of the page reflects the change. https://i.sstatic.net/xjrsx.png I attempted the following: $theme-colors: ("p ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

What is the correct way to maintain focus on a nested scrolling div over another scrolling div with jQuery?

I have encountered an issue with a modal view that contains content extending beyond its boundaries. To remedy this, I applied the overflow-y: scroll property. However, the problem arises when the modal view overlaps with the body, which also has scrolling ...

A chosen class containing a nested class that utilizes the makeStyles function

Can someone explain how to target the 'element' when the root is selected? Here is the makeStyles code snippet: const useStyles = makeStyles(theme => ({ root:{ '&.selected': { } }, element: { } }) And h ...

What is the best way to enable CSS IntelliSense for a Nuxt project?

Currently, I am undertaking a project using Nuxt.js and have set up a Docker image to manage all aspects of it. Additionally, I am looking to integrate MDBVue as a CSS library into my project. After some research, I learned that in order to utilize this li ...

Incorporate zoom feature into the jQuery polaroid gallery

Currently, I am utilizing a jQuery and CSS3 photo gallery found on this website. My goal is to allow the images to enlarge when clicked, however, the method provided by the author isn't very clear to me, as I'm not an expert in jQuery. I attempt ...

CSS Duo-Toned Background

I've been searching everywhere for a solution to this issue. I have a design that I'm attempting to code using divs and CSS. The top half of the image features a gradient that transitions from left to right with different colors. My struggle lies ...

using jquery to select elements based on their data attribute values

I have a question about using jQuery to select an object with a specific data value. For instance: $('[data-infos-parent_id=0]').html('it ok'); <div class="question" data-infos='{"parent_id":0,"my_id":0, "title":""}'> ...

Utilizing anchor tags within the title attribute

I am trying to display a message in a tooltip that includes a link. Here is the HTML code I have used: <div class="col-xs-2" data-toggle="tooltip" title="Please click <a href='www.google.com'>here</a> for more information.">&l ...

What steps do I need to take to make this JavaScript code function properly? How can I create a carbon copy email setup in

Recently, I've been struggling to implement this particular code on my website as I am not very proficient in JavaScript. Despite searching for various online resources, none of them seem to address my issue. This code is meant to be a part of a form ...

Modifying text input in Angular

I am working on an Angular form that includes a text input which I would like to be able to edit by clicking on the edit button. Within the form, there are 3 buttons available: edit, cancel (which discards changes), and save (which saves changes). When t ...

adjustable text size in web view interface

When loading the following html string in a uiwebview, I am trying to set the font-size as a variable value: NSString * htmlString = [NSString stringWithFormat:@"\ <html>\ <s ...

Would adjusting the font sizes of headings be crossing into grey or black hat SEO territory?

Here's the scenario: In this case, the page title is designated as H3, the article title is labeled as H2, and a certain keyword or important sentence is identified as H1 within the content. These elements have custom CSS classes applied to them, cau ...

analyzing information from a variety of HTML tables

I am currently working on extracting financial data from Income Statements tables within 8-K Forms retrieved from the Edgar Database (http://www.sec.gov/edgar/searchedgar/companysearch.html). Here are a couple of examples: Apple Alcoa The specific table ...

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

The code snippet $(this).nextAll("#...").eq(0).text("***") isn't functioning as expected

I am experiencing an issue with the following line of code: $(this).nextAll("#status").eq(0).text("Deleted"). I am trying to insert the text "Deleted" in a <span> tag, but it does not seem to be working... Here is my code: admin.php PHP: $sql = "SE ...

Variances in the order of HTML elements within an article's layout

Check out this example of HTML and CSS <!DOCTYPE html> <html> <head> <title>Floats Example</title> <style type="text/css"> .left { float:left; width:100px; } .righ ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

Tips for changing the color of an underline in an <a> tag when it is hovered over

Is it possible to change the color of the underline in an <a> tag when hovering over it? After some investigation, it seems that direct color changes are not feasible. Instead, you can use the border-bottom option. However, my attempt did not yield ...