How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet:

onChange(event: any) {
    var reader = new FileReader();
    reader.onload = (event: any) => {
        this.url = event.target.result;
    };
    reader.readAsDataURL(event.target.files[0]);
}
#upload-icon {
    align-items: center;
    font-size: 30px;
}

.image-content {
    width: 70px;
    height: 70px;
}

input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    padding: 6px 12px;
    cursor: pointer;
    height: 70px;
    width: 70px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    text-align: center;
    justify-content: center;
}

img {
    border-radius: 50%;
    height: 70px;
    width: 70px;
    object-fit: contain;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<label class="custom-file-upload">
    <input type="file" accept="image/*" capture="environment" class="fileInput" id="file-input"
           (change)="onChange($event)">
    <div class="image-content" *ngIf="!url">
        <i class="far fa-images"></i>
    </div>
    <div class="image-content" *ngIf="url">
        <label for="file-input">
            <img [src]="url"/>
        </label>
    </div>
</label>

The aim is to create a circular shape with a 1px border that displays an icon representing image upload functionality. Clicking on the circle allows users to select an image file, and upon uploading, the circle will show the selected image. To fix the issue of the icon and image not being centered as desired, refer to these images for better understanding: https://i.stack.imgur.com/DVfHD.png and https://i.stack.imgur.com/cAypH.png

Any suggestions on how to resolve this alignment problem?

Answer №1

Ensure that the image and alternate icon are restricted to a maximum height and width of 100%, and change text-align: center; to align-items: center; for the .custom-file-upload class.

Here is the updated HTML -

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<label class="custom-file-upload">
    <input type="file" accept="image/*" capture="environment" class="fileInput" id="file-input"
           (change)="onChange($event)">
    <div class="image-content" *ngIf="!url">
        <i class="far fa-images icon"></i>
    </div>
    <div class="image-content" *ngIf="url">
        <label for="file-input">
            <img [src]="url"/>
        </label>
    </div>
</label>

And here is the updated CSS -

#upload-icon {
  align-items: center;
  font-size: 30px;
}

 .image-content {
  max-width: 100%;
  max-height: 100%;
}

input[type='file'] {
  display: none;
}

.custom-file-upload {
  border: 1px solid #ccc;
  padding: 12px;
  cursor: pointer;
  height: 70px;
  width: 70px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

img,
.icon {
  max-height: 100%;
  max-width: 100%;
}

Try out this example on StackBlitz

If you want to fill the entire division, consider using the image as a background image - see an example here

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

Issue: Module './App' not found in webpackSolution: Check if the module path is

I've decided to switch my .js files to .tsx in order to start using TypeScript. To incorporate TypeScript, I used the following command: yarn add typescript @types/node @types/react @types/react-dom @types/jest and began converting first index.tsx fo ...

The Google map is failing to load on the webpage

My id="ieatmaps" is set up to call the googlemaps.js, but for some reason, it's not displaying correctly. I must be missing something. function initMap() { var map = new google.maps.Map(document.getElementById('ieatmaps'), { c ...

Determine the card type based on the card number

My array of card types is structured like this: var cards = new Array(); cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: tr ...

Would it be considered poor design to send back a partial view with just a simple JavaScript alert in my ASP.NET MVC application?

I have a unique Action method that handles exceptions by returning an _error partial view: [AcceptVerbs(HttpVerbs.Post)] public PartialViewResult Register(string id, int classid) { try { Thread.Sleep(3000); User user = r.FindUser(i ...

Glitch in Safari 6: Round Corners Issue

Greetings! Upon observing the image provided, an unusual behavior can be noticed in Safari 6 concerning round corners. { border-radius: 5px 5px 5px 5px; } Upon hovering over the elements, a thin line appears that seems to accumulate with each subsequent ...

HTML - No alterations to Writing Mode

Hello everyone, I'm attempting to display a header vertically in my table but the writing-mode property is not having any effect. CSS .VerticalText { writing-mode: tb-rl; } HTML <td rowspan="6" id="tableHeader" class="Border"> <h1 cl ...

Enhancing User Experience in VueJS with Pug Templates and Transitions

Managing multiple 'pages' of content within a multi-step process can be challenging, especially when trying to incorporate VueJS's transition feature for a carousel-like slide in/out effect. The contents being transitioned are stored in sepa ...

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Invoke a controller in Prestashop by utilizing AJAX technology

I am struggling to figure out how to call the method / function in my controller. The controller is named TestController.php, and I also have files named Test.tpl and Test.js. Additionally, I am unsure of what to put in the URL field. My goal is to retrie ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

Loop through the coefficients of a polynomial created from a string using JavaScript

Summary: Seeking a method to generate a polynomial from specified coordinates, enabling coefficient iteration and optional point evaluation I am currently developing a basic JavaScript/TypeScript algorithm for KZG commitments, which involves multiplying c ...

Utilize a JSP dynamic array to insert dynamic information into a database

I need to insert data into my database, extracted from a dynamically created table by the user with 2 columns (ID,Name) How can I retrieve each individual row that was inserted by the user and add it to the database? It's important to note that this ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Enter your phone number in the designated field

I am looking to receive mobile numbers from various countries as input. I attempted to achieve this using the following code: <input type="tel" minlength="8" maxlength="10" name="Number" id="Number" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" class="form-co ...

Incorporating aws-sdk into Angular 2 for enhanced functionality

I'm currently working on integrating my Angular2 application with an s3 bucket on my AWS account for reading and writing data. In the past, we used the aws-sdk in AngularJS (and most other projects), so I assumed that the same would apply to Angular2 ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

The error message encountered while using String.search("sinh(2"): "Regular expression is invalid."

Encountering an issue: var test = $("#k_w").val().search("sinh("+parseFloat(sinh_array[i])); An error message is displayed by the debugger: Uncaught SyntaxError: Invalid regular expression: /sinh(2/: Unterminated group. sinh_array[i] represents numerica ...

How can I clear my object so that new Dates() can be added to my calendar?

I am working on updating my program to seamlessly replace old JSON data from a holidays API with new data as soon as it is received. Initially, I attempted to declare the array as empty at the start, but this approach did not yield the desired results. Si ...