The positioning of absolute CSS elements is causing alignment issues with their adjacent siblings

I am currently developing a customized Tooltip component using React that can be rendered to the right or below the target element. In my approach, the Tooltip component takes children as input and displays them. When these children are hovered over, the tooltip appears through CSS classes with absolute positioning. Everything works perfectly when the elements are arranged in a column and the tooltip is set to appear on the right. However, a misalignment issue arises when the elements are arranged in a row with the tooltip rendering below the child, seemingly due to the length of the tooltip text pushing it off-center.

To see this issue in action, you can visit this codesandbox link. Click the button to switch the layout from column to row and hover over the elements to observe the misalignment:

https://codesandbox.io/s/busted-tooltip-obf0h1?file=/src/Tooltip.scss

I need help aligning the tooltips centrally with their respective child elements when they render below them. How can I achieve this?

// CustomTooltip.jsx

import React, { useState } from 'react';
import './Tooltip.scss';

const Tooltip = ({ children, label, orientation = 'right' }) => {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div className={`Tooltip__Container ${orientation}`}>
      <div
        onMouseOver={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {children}
      </div>
      <div className={`Tooltip__Inner ${orientation} ${isHovered ? 'Visible' : ''}`}>
        {orientation === 'right' && <div className={`Tooltip__PointLeft ${isHovered ? 'Visible' : ''}`} />}
        {orientation === 'bottom' && <div className={`Tooltip__PointUp ${isHovered ? 'Visible' : ''}`} />}
        <div className={`Tooltip ${orientation} ${isHovered ? 'Visible' : ''}`}>
          {label}
        </div>
      </div>
    </div>
  );
};

export default Tooltip;
/* Tooltip.scss */

@import 'src/styles/colors.scss', 'src/styles/typography.scss', 'src/styles/breakpoints.scss';

.Tooltip__Container {
  display: flex;
  position: relative;

  &.right {
    flex-direction: row;
  }

  &.bottom {
    flex-direction: column;
  }
}

.Tooltip__Inner {
  display: flex;
  z-index: -1;
  position: absolute;
  transition: all .25s ease;
  opacity: 0;
  left: 0;
  top: 0;

  &.right {
    flex-direction: row;
  }

  &.bottom {
    flex-direction: column;
  }
}

.Tooltip__Inner.right.Visible {
  opacity: 1;
  left: 3.5rem;
}

.Tooltip__Inner.bottom.Visible {
  opacity: 1;
  top: 3.5rem;
}

.Tooltip__PointLeft.Visible {
  opacity: 1;
  width: 0; 
  height: 0; 
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent; 
  border-right: 10px solid $white-transparent;
  align-self: center;
  justify-self: center;
}

.Tooltip__PointUp.Visible {
  opacity: 1;
  width: 0; 
  height: 0; 
  width: 0; 
  height: 0; 
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid $white-transparent;
  align-self: center;
  justify-self: center;
}

.Tooltip {
  background-color: $white-transparent;
  padding: .75rem;
  border-radius: 3px;

  @include MainFont;
  color: white;
}

Answer №1

To find a fast fix, consider modifying the lower class within .Tooltip__Inner

using the following code:

  &.lower {
    flex-direction: column;
    left: 50%;
    -ms-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
  
  }

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

Font Awesome icon not displaying properly in Laravel 5.8, showing as a square instead

Having trouble getting the icon to display in my project as it's showing up as a square when using Font Awesome. I'm utilizing npm packet management. This is the snippet from my app.scss file: // Variables @import 'variables'; // Fo ...

Experiencing Issues in Building with React Firebase Hooks and Vite

While attempting to compile my react project using vite, I encountered the following error message. node_modules/react-firebase-hooks/auth/dist/auth/types.d.ts:2:50 - error TS2304: Cannot find name 'AuthActionHook'. 2 export declare type EmailA ...

Component rendering based on conditions is not working properly when using Next.js, especially on the initial load

While utilizing Ant Design and a Custom Stylesheet, I have encountered an issue where the style appears broken upon first load. However, if I navigate to another page and return to the original broken page, it displays correctly. This problem only occurs d ...

Steps for saving data to a JSON file in a React application

Looking to update a json file with some data. The current contents of the JSON file are: [{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info": ...

Aligning the image at the center within a flex container

I am struggling with aligning an image and a link inside a div using the display: flex property. This is how my code looks: <div style="display: flex;"> <div class="site-title-container"> <img style="border-radius: 7px; width: 34px; h ...

Tips for aligning words on a single line

Encountering an issue with long words being split up in the middle of a line, as shown in this photo: https://i.stack.imgur.com/IxQi6.png This is the code snippet causing the problem: ineligiblePointsTableRows() { return this.state[PointsTableType. ...

incapable of acquiring/displaying the entered data

I'm attempting to update a user's name in React by filling out an input field and clicking a button. However, my code is not functioning as expected. I am fairly new to React, so any help would be appreciated! Here's what my code looks like ...

Is there a way to locate a null string within this data arrangement?

I am looking to create functionality where, when a button is clicked, the application checks the state and takes different actions based on the result. Specifically, I want to ensure that there are no empty "value" fields, and if there are, redirect to ano ...

Attempting to fetch data using the useEffect hook and context API

I am working on displaying state information within a component. Utilizing context to retrieve data from various sources. const router = useRouter() const [sidebarOpen, setSidebarOpen] = useState(false) const [loadUser, setLoadUser] = useState({}) ...

Issue: React/Redux component fails to update after clicking on checkbox

I have checkboxes in my component that I want to save in the redux state when clicked, and update the component to display the selected checkbox as checked. Here is my component: import React, {Component} from 'react'; import {connect} from &apo ...

What is the best way to determine the position of an element with text content

Currently facing an issue with positioning in my project. Attached is a snapshot of my desired layout. I've tried creating a starburst effect and adding text using this code: jsfiddle link, but I'm struggling to position the elements correctly ...

Using a zoom background image in an HTML document without any accompanying text

I am trying to create a zoom effect on a background image without affecting the text overlaying it. Here is the CSS code: .page1-box { width: 1200px; height:800px; overflow:hidden; } .page1 { width: 100%; height: 100%; background: ...

Tips for applying a CSS wrapper to an element, not just text

I am working with a group of span elements within a td that has a set width. My goal is to wrap the span elements onto new lines without breaking up the text inside them. For example, if I have: <td> <span>bind</span> <span&g ...

Components drifting apart following viewport adjustments

Can someone help me with this issue in responsiveness? When I change the viewport, my header and main elements seem to be moving far apart from each other. View the code on JSFiddle <header> <div class="slider"> <img src="picture1" al ...

Guidelines for pinpointing local directories

Recently, I obtained a source code for a website navigation that includes a unique set of icons known as "Typicon." The HTML in the source code contains the following: <link rel="stylesheet" type="text/css" href="css/component.css" /> Within the C ...

Experience the dynamic trio of ReactJS, Redux, and pagination for

I have an API endpoint that provides an array of ingredients. Each ingredient has unique properties such as id, name, measurement unit, density (kg/lt), and cost per measurement unit. The list of ingredients is constantly growing, with thousands already in ...

What is the best way to increase the height of an image in a grid container beyond the height of

I am currently designing a grid layout to showcase recent articles. Each article includes an image and a brief description. My goal is to have the image taller than the content text block, while ensuring responsiveness across various screen sizes. Below i ...

Tips for centering a list using flexbox technique

I have 3 boxes stacked vertically using flexbox, currently positioned to the left. I am looking for a more elegant solution to center them horizontally without compromising the layout. I attempted using margin: 10px auto on a div which seemed awkward in th ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

What could be causing my col-x to not function correctly in Bootstrap?

I am trying to modify my Bootstrap navbar by adding a Login button, but I encountered an issue. When I use col-x classes inside the navbar to separate elements equally, they only cover 50% of the width and no more. However, using col-x classes outside the ...