"Having trouble centering an image within a flex container even after setting specific width and height parameters

I have been working on my personal portfolio using CSS flexbox. My goal is to center the image horizontally, and I was successful in doing so. However, when I defined the width and height for the img, the image shifted to the left instead of staying centered.

When centered without defining the width and height, this is how it looks:

.center-img{
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}
<div class="center-img">
  <img src="https://randomimage.com" alt="user">
  <h1>User</h1>
</div>

And after defining the width and height, it looked like this:

.center-img{
  width:100px;
  height:100px;
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}
<div class="center-img">
  <img src="https://randomimage.com" alt="user">
  <h1>User</h1>
</div>

I expected that defining the width and height of the image would not affect its position, and it should remain centered. Thank you!

Answer №1

Here are a few key points to keep in mind:

  1. Ensure the image is centered properly.

    In your initial code snippet, the image appeared centered because it took up the entire width of the viewport. When you resized the image using width and height, it defaulted to aligning left. To center flex items horizontally in a column layout container, use align-items.

  2. Avoid using images as flex items due to potential bugs.

    Using images as flex items can lead to rendering issues in various browsers. Instead, encapsulate the image within a div element and make that div the flex item.

  3. Center the image within a nested container using flex properties.

    Utilize a nested flex container to centrally position the image.

.center-img {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: lightgray;
}

.center-img > div {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  border: 1px dashed red;
  
}

.center-img > div > img {
  width: 100%;
}

h1 {
  margin: 0;
}
<div class="center-img">
  <div>
    <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
      alt="user">
  </div>
  <h1>User</h1>
</div>

Answer №2

To make the image centered, apply height and width to the img element only and include align-items: center in the CSS rules as shown below:

.center-img {
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

img {
 width: 100px;
 height: 100px;
}
<div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
            alt="user">
 <h1>User</h1>
</div>

Answer №3

To effectively manage the size of the elements within, you must wrangle their dimensions.

The size of the image can be adjusted using max-width and max-height in relation to the container. A red border has been added for visibility of the container.

In addition, the default settings for the h1 element include a large font-size and margin, which need to be customized as well.

.center-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center; /* switch text-align to align-items */
  border: 1px red solid; /* added for clearer container visualization */
}

.center-img img {
  max-width: 100%; /* adjust according to container size */
  max-height: 40%; /* adjust based on container size */
  height: auto; /* maintain aspect ratio */
  width: auto; /* maintain aspect ratio */
}

.center-img h1 {
  margin: 5px 0 0; /* adjust default margins for h1 */
  font-size: 18px; /* customize to an appropriate size */
}
<div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
    alt="user">
  <h1>User</h1>
</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

Using Ajax to dynamically load content from one div to another div

Trying to get the hang of using ajax to switch up the content within a div (as html) when clicking on a link in that same div. My ajax skills are definitely lacking, so I'm sure this is a noob question. Despite my efforts to find solutions online, not ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

What is the best way to showcase AJAX data within a complex HTML structure?

I need assistance with displaying the JSON output in my HTML code. My current HTML code is quite complex, so I am unsure how to include this data and repeat the HTML section for every JSON element. Can you provide guidance on how to achieve this? HTML COD ...

Radio button selection state dependent on other value in table row

I am facing a scenario where I need to choose different options using checkboxes in a table and simultaneously select a default row through a radio button. The idea is to set overall permissions with checkboxes, and then select the default access permissio ...

I'm looking to incorporate jQuery UI classes into my custom CSS file on a per-element basis. Is there a way

How can I incorporate jQuery UI classes into my CSS file on a per-element basis, like this: input { ui-corner-all /* <- JQuery UI class */ } Instead of adding the class to every input individually, like this: ...

"Placing an image at the bottom within a DIV container in HTML

My goal is to neatly align a group of images at the bottom of a fixed-height div. The images all have the same height and width, making the alignment easier. Here is the current structure of my code: <div id="randomContainer"> <div id="image ...

Adjust the CSS extension within the about:config settings of Firefox

I've been using the Zotero extension and I want to adjust how TinyMCE handles paragraph spacing. I'm looking to customize the CSS in extensions.zotero.note.css by adding specific CSS rules. The reason I want to make these changes is because I fe ...

Unique events catered to specific devices: mobile vs. desktop

When a user clicks on the login icon from a desktop, I want a modal dialog to appear. However, when using smaller devices like mobile or tablets, I prefer that a reactjs route is triggered to display in the main content area instead of using a modal dialog ...

Issue with Material UI Menu positioning incorrectly when button is aligned to the right or left

When looking at the first image, it appears that the material-UI menu position is working correctly. However, when we change the button position to align-right, the menu position shifts slightly to the left, not perfectly aligning with the right side as in ...

Ways to Remove Focus from a Button in Blazor/C# by Triggering the Escape Key without JavaScript

I am in the process of developing a tooltip feature within the Blazor framework. The main goal I have is to make the tooltip disappear when the escape key is pressed while focusing on the button. Currently, I have successfully implemented this feature usi ...

Developing a PHP switch statement to alternate between different stylesheets based on specific

I've encountered a challenge while trying to create a button on my website that switches the stylesheet back and forth. The button is functioning properly, but whenever I click on it from a page other than the homepage, it keeps switching back to the ...

CSS fails to style links

Apologies in advance for the seemingly trivial and highly specific question, but I'm really struggling with this one. I'm attempting to style two <li> elements that are nested within a <nav><ul><li><a href="" ...

Update table content dynamically without the need to refresh the entire page while maintaining the original CSS

I have been encountering an issue with my ASP .NET code. I have spent hours researching but haven't found a solution that works for me. My problem is that when I click a button, the text inside a textbox should be added to a dropdown and update a tabl ...

Using shifting label field (in CSS) without the need for a required attribute

My challenge involves creating a floating label for a styled input using only CSS. The issue arises when I realize that this implementation requires the input to have the required attribute in order for the label to function properly (using pure CSS). Is t ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Switching from cURL to Ajax resulted in receiving a 400 Error code

My goal is to save specific URLs into a jsonbox, but I keep encountering Error 400. The curl command provided in the documentation is as follows: curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \ -H 'content-type: applic ...

Javascript - Conceal a Dynamic Div Depending on its Text

I have a unique table that generates dynamic Divs with ID's that count as they are created in the following format: <div id="dgpCheckDiv10_0"> <input Delete </div> <div id="dgpCheckDiv10_1"> text2 </div> Some of t ...

Is there a way to create a link in Javascript that directs to a specific div on a new

Is there a way to create a link that not only opens a new page but also automatically scrolls to a specific section within that page? ...

Positioning CSS icons beside text

I'm having trouble aligning a close button I created in CSS with regular text. Although the containing span element seems to align with the adjacent text, it doesn't align properly with the child divs. <a class="event-filter button" href="#"& ...

Adjusting the border color when two checkboxes are chosen (and simultaneously deactivating the others)

I'm struggling to understand how to disable the remaining checkboxes after two are selected and change the border color of the "checkbox_group" to red. Can someone help me with this? Here is the JavaScript code I have so far: $(document).ready(funct ...