What is the best way to align a badge icon regardless of the avatar's size?

I'm working on creating an avatar component with badges. However, I'm facing an issue with the positioning of the badges relative to the avatar size.

The image below provides a clear illustration of the problem. Can you guide me on adjusting the positioning to ensure it's correct irrespective of the avatar's size?

Here's the code I've implemented on codesandbox

Thank you for your assistance in advance.

https://i.sstatic.net/wiQxl.png

import React from "react";
import BadgeSvg from "./BadgeSvg";
import "./avatar.scss";

const Avatar = ({ size }) => {
  const image = "https://i.imgur.com/pKHO357.png";

  return (
    <div>
      <div className={`content-icon ${size}`}>
        <img
          src={image}
          alt="Avatar Image"
          className={`content-icon ${size}`}
        />
      </div>
      <div className="badge">
        <BadgeSvg size={size} />
      </div>
    </div>
  );
};

export default Avatar;
.content-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  border-radius: 50%;
  background-color: #f2f2f2;
  object-fit: cover;
  color: #999999;

  &.xsmall {
    width: 16px;
    height: 16px;
  }

  &.small {
    width: 32px;
    height: 32px;
  }

  &.medium {
    width: 40px;
    height: 40px;
  }

  &.large {
    width: 72px;
    height: 72px;
  }

  &.xlarge {
    width: 96px;
    height: 96px;
  }
}

.badge {
  position: relative;
  top: -18px;
  right: -52px;
  display: flex;
  width: min-content;
}

Answer №1

If you restructure your JSX, you can address the problem with CSS absolute and relative positioning. However, for perfect alignment, you may need to manually adjust some CSS properties as shown below.

Below is the code for your Avatar component:

import React from "react";
import BadgeSvg from "./BadgeSvg";
import "./avatar.scss";

const Avatar = ({ size }) => {
  const image = "https://i.imgur.com/pKHO357.png";

  const getRightValue = (aSize) => {
    if (aSize === "medium") {
      return { right: "-3px" };
    }

    if (aSize === "xlarge") {
      return { right: "5px" };
    }

    if (aSize === "large") {
      return { right: 0 };
    }
  };

  return (
    <div>
      <div className={`content-icon ${size}`}>
        <img
          src={image}
          alt="Avatar Image"
          className={`content-icon ${size}`}
        />
        <div className="badge" style={getRightValue(size)}>
          <BadgeSvg size={size} />
        </div>
      </div>
    </div>
  );
};

export default Avatar;

Below is the final CSS code:

.content-icon {
  position: relative;
  /* rest of css */
}

.badge {
  position: absolute;
  bottom: 0;
}

And here is the final output. Hopefully this solution helps.

https://i.sstatic.net/XxuxA.png

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

merge various CSS styles into a single one

My div has a mix of styles applied to it. <div class="alert alert-secondary login-alert" role="alert">Please contact the administrator to receive credentials!</div> The styles alert and alert-secondary are default styles from bootstrap 4, whi ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Generate Bootstrap 5 Navbar <li> and <ul dropdown item> dynamically using JavaScript

Requesting assistance I have stored text in the constant.js file as shown below. export const navLinks = [ { id: "manage", title: "Manage", }, { id: "transactions", title: "Tran ...

I successfully converted a d3 chart to a base64 image format and now I am looking to share it on Facebook using either client-side JavaScript or Angular

After generating a base64 image from a cool d3 chart, my next challenge is figuring out how to share it on Facebook using either client-side javascript or Angular. Any suggestions? ...

Encountering difficulties in npm installation of redux and datepicker

Attempted to use the npm command below to install redux, react-datepicker, and react-router-dom. npm i react-redux @reduxjs/toolkit react-datepicker react-router-dom@6 Realized that package.json was not being updated and received the following message in ...

Error: The createContext function is designed for use only in Client Components. To enable it, include the "use client" directive at the beginning of the file

After creating a fresh Next.js application with the app folder, I proceeded to integrate Materiel UI following the example provided in the documentation. However, I encountered an error: TypeError: createContext only works in Client Components. Add the & ...

What sets npm node-sass apart from npm sass?

Recently, I discovered that the recommended approach is to utilize @use rather than @import in sass. However, it appears that using npm sass instead of npm node-sass is necessary for this. Can you clarify the distinction between these two? Also, why do @ ...

Ways to create diagonal or vertical table breaks using CSS

If you have a <table> that is very tall or wide and you want it to wrap for screen display, how can this be achieved using CSS? For example, a table that is 300% page height and 30% page width would be divided into three parts. # # # # # # beco ...

What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object. How can I dynamically set the @click event in a v-for loop? I attempted to use this.m1, "this.m1", "m1", but encountered an error: fns.apply is not a function. Javascript: new Vue ...

Sharing State with a Secure Route in Vue Router (using the script setup method)

Hello everyone, I'm encountering an issue while trying to send a state to the protected routes in vue-router. The error that I faced mentioned "Discarded invalid param(s) "_id", "dish_name", "description", "img" ...

Move a div element as you scroll down the page

I currently have a div that appears when a user scrolls down a page. When clicked, it sends you back to the top of the page. Right now, it simply fades in and out, but I would like it to slide in from the right side of the page. Below is my existing code: ...

Menu options

I am currently working on developing a mouseover navigation website. Initially, my design included main buttons for "Our Team", Locations, and Patient Resources. Here is the basic structure I had before attempting to switch to a mouseover approach... &l ...

Slick Slider isn't compatible with Bootstrap Tab functionality

I'm having an issue with using slick slider within a Bootstrap tab menu. The first tab displays the slick slider correctly, but when I switch to the second tab, only one image is shown. How can I resolve this problem? <!DOCTYPE html> <html ...

Display laravel view using JavaScript Ajax

I seem to be facing a challenge in displaying the desired view after invoking the controller method via Ajax. Below is the JavaScript function where I trigger the controller Method 'create_pedido' using an Ajax post request. $('.small-box&a ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Having trouble with triggering a Material UI modal from a Material UI AppBar on a Next.js page

As a newcomer to the world of React.js and Next.js, I am encountering difficulties when trying to open a Material UI modal from a Material UI AppBar within a Next.js page. Most of the code I have implemented here is directly copied from the Material UI we ...

Basic Block - Three.JS

My goal was to create a simple rotating 3D cube using the Three.js library for WebGL. Despite following numerous tutorials, I can't figure out why my code only displays a black screen with no geometry. //Setting window dimensions var width = windo ...

What is the best way to showcase distinct sections from several web pages on a single webpage?

I want to showcase multiple web pages on a single page using Iframes. What is the best way to achieve this and display them all together? ...