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

React's componentDidMount fails to trigger for jQuery AJAX request

Here is my code snippet: import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { constructor(props) { super(props); this.state = { data: '' }; ...

Is it possible to change label text using CSS without referencing the element by its ID?

Here is a simple code snippet: <div class="delem"><label class="required" for="last_name">Full Name :</label><input id="fullname" type="text" name="fullname" value="" class="fullsize" required=""></div> <div class="delem" ...

"Exploring the best locations for storing CSS, JS, and image files in Spring

Having trouble figuring out where to place my public files. I attempted the solution mentioned in this thread on Stack Overflow but it didn't work for me. I've tried putting my public folder in various locations within the WEB-INF directory, but ...

How to evenly size overlay divs with CSS

I currently have two divs positioned on top of each other with the following CSS: div.container { position: relative; min-height: 100%; margin:0; padding:0; background:url('http://www.scratchprogramming.org/img/book.png'); ...

Is it common practice to make an API request in Next.js?

Presently, my backend is in NodeJS (Express) and I am currently transitioning from create-react-app to NextJS on the frontend. Should I continue making API requests from NextJS to the Express server or should I consider moving the APIs to NextJS itself so ...

React Prop Local Modal Redux

Just diving into the world of React and Redux, and I'm a bit lost on how to effectively utilize both local properties and redux properties simultaneously. After trying different approaches without success, I'm reaching out for guidance. My goal i ...

Optimal strategy for modifying the MUI Drawer's content

I'm brand new to React and I'm trying to figure out the most effective way to create a simple transition of body content using React + MUI + Drawer. The code snippet below is completely incorrect and just for demonstration purposes: return ( ...

Looking for assistance with CSS positioning techniques

Creating a dropdown list with a caret icon for each item is my goal, but I'm facing some challenges. Here's the code snippet of the div structure: <div class="class-to-div1" id="{{ div.id }}" data-cardsnum="{{ div.num }}"> <div clas ...

Instructions for triggering a function upon an onClick event in ReactJs

I have a handleClick event that should run the renderDetail function in the {this.state.ShowInfo[i]} div when clicked. I have implemented it as shown below, but using callbacks did not work. class App extends React.Component { constructor(props) { super ...

Is it possible to define the sequence of wrapped items in CSS flexbox?

I am using a <div> with CSS flex to maintain responsiveness. I want to control the order in which elements are wrapped. For instance, I need 1 - 2 - 3 To be rearranged as 1 3 2 Once fully wrapped. Here is my current code: https://jsfiddle.net/ ...

What are some creative ways to design drop-down menus within an email?

The snippet of code I am currently using lacks the ability to format text, and it does not allow content below dropdown items to shift down properly in an email. <select> <option value="first">First-time users of the Vanguard Events app:&l ...

Search filter bar does not seem to be appearing

I've been working on developing a filtering search bar to organize and sift through a specific dataset retrieved from an API. Despite successfully compiling the code, I'm facing an issue where the input designated for creating the search bar is n ...

How can I retrieve the accessKey and Secret key from an AWS identity pool using React.js?

For further clarification, I am working on a react application with 3 input fields that are managed using the useState() Hooks. <input type="text" name="username" value={state.username} onInput={} /> <input type="password& ...

React JS - Large image failing to display entirely

I'm currently facing challenges with displaying my image in full size. I am unsure what is causing this issue and would appreciate any guidance on correcting my approach. The specific image I am attempting to display at full-size can be found Howeve ...

Is it possible to style the parent CSS file using a query?

Is it feasible to achieve this, or are there alternative methods to accomplish something similar? In a CSS file, we have the ability to set queries for various screen resolutions, allowing CSS rules to apply only to specific screens. @media (max-width: 76 ...

Modifying the color of a placeholder in an HTML input using CSS

Version 4 of Chrome now supports the placeholder attribute on input[type=text] elements (and likely other browsers do too). Despite this, the following CSS code does not affect the color of the placeholder text: input[placeholder], [placeholder], *[pla ...

The Swig template displays the output tag prior to processing the content

Currently, I am developing an isomorphic React/Flux application and utilizing Swig for rendering the content. However, upon opening the site, a blank page briefly appears with the placeholder {{ html|safe }} output tag before displaying the actual content ...

Cypress - Locate and interact with a button containing specific text

Utilizing material-ui as my go-to css framework, I'm seeking to target a button that includes specific text. Here is my current code: cy.get('button').contains('Edit Claim').should('be.disabled'); The issue arises becaus ...

Highlight react-bootstrap NavItems with a underline on scroll in React

I am currently working on a website where I have implemented a react-bootstrap navbar with several Nav items. My goal is to enable smooth scrolling through the page, where each section corresponds to an underlined NavItem in the navbar or when clicked, aut ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...