What could be causing the image to not align properly when using flex direction column and align-items=center?

Encountering an issue with image centering in a flexbox set to direction:column.

Imagine two elements within a flexbox, the first containing an image:

<div class="container">
    <div class="image-container">
        <img class="img" src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg">
    </div>
    <div class="another-flex-child">
        Random content here
    </div>
</div>


.container {
  height: 300px;
  background-color: green;
  display: flex;
  flex-direction: column;

  .image-container {
    flex: 1;
    align-self: center;

    .img {
      height: 100%;
    }
  }

  .another-flex-child {
    flex: none;
    background-color: red;
  }
}

Expected the image to be centered horizontally in the div, but instead, its left border aligns with the center of the div.

Replacing the image with a text-containing div shows the expected centering behavior.

Curious to understand why this discrepancy occurs.

View this fiddle for reference

Answer №1

When your image-containing <div> has align-self: center, it becomes a block-level element with a default width of 100%, thus being constrained by its parent.

To properly center the image, you can use display: contents like so:

.container .image-container {
  display: inline;
}

Here's an example implementation:

.container {
  height: 300px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.container .image-container {
  flex: 1;
  align-self: center;
  display: contents;
}

.container .image-container .img {
  height: 100%;
}

.another-flex-child {
  flex: none;
  background-color: red;
}

.spacer {
  height: 20px;
}
<div class="container">
  <div class="image-container">
    <img class="img" src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg">
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

<div class="spacer"></div>

<div class="container">
  <div class="image-container">
    <div>Properly centered content</div>
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

Answer №2

There is an issue with utilizing an SVG that lacks intrinsic dimensions and only has an intrinsic ratio. As a result, it appears as if your image has a width of 0, causing its centered container to also have a width of 0.

Here is the code before adding height:100%:

.container {
  height: 300px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.image-container {
  flex: 1;
  align-self: center;
  border:2px solid blue;
}

.img {
  /*height: 100%;*/
}

.another-flex-child {
  flex: none;
  background-color: red;
}

.spacer {
  height: 20px;
}
<div class="container">
  <div class="image-container">
    <img class="img" src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg">
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

<div class="spacer"></div>

<div class="container">
  <div class="image-container">
    <div>Properly centered content</div>
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

By setting height:100%, the image will occupy all available space while maintaining its aspect ratio. However, this can lead to overflow issues because the browser does not recalculate the container's width:

.container {
  height: 300px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.image-container {
  flex: 1;
  align-self: center;
  border:2px solid blue;
}

.img {
  height: 100%;
}

.another-flex-child {
  flex: none;
  background-color: red;
}

.spacer {
  height: 20px;
}
<div class="container">
  <div class="image-container">
    <img class="img" src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg" >
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

<div class="spacer"></div>

<div class="container">
  <div class="image-container">
    <div>Properly centered content</div>
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

To prevent this issue, assign a width to the image and ensure to include min-height:0 in the container to allow for shrinking:

.container {
  height: 300px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.image-container {
  flex: 1;
  align-self: center;
  border:2px solid blue;
  min-height:0;
}

.img {
  height: 100%;
}

.another-flex-child {
  flex: none;
  background-color: red;
}

.spacer {
  height: 20px;
}
<div class="container">
  <div class="image-container">
    <img class="img" src="https://interactive-examples.mdn.mozilla.net/media/examples/firefox-logo.svg" width="250">
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>

<div class="spacer"></div>

<div class="container">
  <div class="image-container">
    <div>Properly centered content</div>
  </div>
  <div class="another-flex-child">
    Random content here
  </div>
</div>


...

Answer №3

Include the justify-content property in your CSS code as shown:

.image-container {
    flex: 1;
    align-self: center;
    justify-content:center;
}

This adjustment should resolve the issue.

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

Invalid Operation: The value 'undefined' cannot be used as a function

I've been working on implementing a date picker feature for an HTML form. In the HTML header, I have included the following script: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> The script I&apo ...

Is it possible to hide a div using Media Queries until the screen size becomes small enough?

Whenever the screen size shrinks, my navbar sections start getting closer together until they eventually disappear. I've implemented a button for a dropdown menu to replace the navbar links, but I can't seem to make it visible only on screens wit ...

Is there a way to ensure uniform display of HTML form error messages across various browsers?

Recently, I completed a login form that consists of username and password fields. For the username, I used a text field with the type email, while for the password, I utilized a text field with the type password which requires validation through a regex pa ...

Generating a clickable link from information pulled from a database and utilizing the get() method

Currently experimenting with a form I created and everything is functioning smoothly. My current objective involves retrieving specific rows from my database and presenting them as a summary on a separate page. However, I want these rows to appear as hyper ...

Error: Trying to prepare a statement on an invalid PDO object in PHP

I'm facing an issue while attempting to execute a query using database credentials from a configuration file. I keep encountering the error message: Uncaught Error: Call to a member function prepare() on null This is my config.php file: $host = &apo ...

Positioning one div beneath another div

As a newcomer to the world of web development, I'm struggling with alignment in my project. Specifically, I have an issue with the features area - every time I add it, it appears above where I want it, below the search bar and image. View example Her ...

The elements within the flexbox are being truncated when viewed on smaller devices

I have encountered an issue with my code where the .content element, which has flex properties, appears cut off on small screens. I want to avoid setting a fixed size because the text within it may vary in size. The goal is for the background image to fi ...

Conceal a table with jQuery

Is there a way to initially conceal a table on page load only to reveal it with a sliding animation when a specific link is clicked? I have attempted using the following code to hide the table: $('.table_div').hide(); I have enclosed the table ...

Creating dynamic web pages using Smarty templating engine to render HTML

I'm attempting to display my unprocessed HTML content using Smarty. {if !empty($brand.description)} {$brand.description} {/if} Although the initial text includes spaces and line breaks, when viewed, the HTML appears as plain text. I also experimen ...

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...

Tips for toggling the radio button value to either checked or unchecked state

<input type="radio" name="imgsel" value="" checked /> I am looking to have a radio button that is initially checked with a value of 'present'. When the button is unchecked, I want the value to change to &apos ...

Using jQuery to target all rows and select the input within a td

I am attempting to calculate the values within a table by capturing changes in the input fields. Below is an example of the HTML table being addressed and the jQuery code I am using to extract values from all input fields by iterating through the rows usin ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

Stop video and audio playback in an android webview

Is there a way to pause audio and video in an Android WebView without disrupting the page rendering? I have tried various methods but haven't found one that successfully pauses both the sound and the video without affecting the WebView. webView.onPau ...

Modify the text of a button when hovered over (JavaFX)

Can anyone help me figure out how to change the text of a button when it is hovered over? Approach: if (button.isHover()){ button.setText("new message"); } I'm open to either a css fix or a code solution! ...

What is the best way to set conditions for document side script?

I'm struggling to disable the horizontal scroll when the viewport width is 480px or less. The script that controls the scroll behavior on my website looks like this: <script> $(function () { $("#wrapper").wrapInner("< ...

The One-time-password (OTP) page fails to display following the successful transmission of the OTP to the user through PHP

I've hit a bump in my class project and could use some help. Currently, I'm working on a login form that requires users to enter a one-time password sent to their email for authorization. Successfully, the one-time password (OTP) and the curren ...

Enabling a JSON file property to be clickable as needed

I am working with a JSON file obtained from an API call, which contains various objects. My goal is to display the message property of each object, some of which may contain hyperlinks within the message. Here is the HTML code I have implemented to make t ...

What is causing the additional space at the bottom?

Why does my centered black border triangle have an extra bottom margin causing a scroll bar to appear? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 100vh; width: 100%; background: blue; } .canvas { border: 10px s ...

Reveal content as you scroll

I'm having trouble with the code snippet below. My goal is to utilize .cbp-fbscroller in my CSS to show a new side navigation menu on my HTML page only when scrolling down to 900px. However, as someone who is new to JavaScript, I am struggling to make ...