I've been trying to create an effect similar to this one: whenever a div is hovered a bigger div covers it showing more details about the card. This is the jsx code(All classes are Tailwind css classes):
import "../../App.css";
import { useState, useRef } from "react";
function List() {
const cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
return (
<div>
<h2 className="text-white pl-[4%] text-[1.3vw] font-semibold">
List Heading
</h2>
<div className="flex space-x-2 pt-[1%] pl-[4%] overflow-x-scroll overflow-y-hidden">
<Card num="1" />
<Card num="2" />
<Card num="3" />
<Card num="4" />
<Card num="5" />
<Card num="6" />
<Card num="7" />
<Card num="8" />
<Card num="9" />
<Card num="10" />
</div>
</div>
);
}
function Card(props) {
const [classes, setClasses] = useState("bg-yellow-300 h-[8.6vw] w-[15vw]");
const divRef = useRef();
function cardHovered() {
const rect = divRef.current.getBoundingClientRect();
let posX = rect.x;
let posY = rect.y;
console.log("x-axis: " + posX);
console.log("y-axis: " + posY);
setClasses(
`h-[18vw] w-[22vw] bg-black opacity-50 z-10 absolute left-[${posX}px] top-[${posY}px]`
);
}
function cardUnhovered() {
setClasses("hidden");
}
return (
<div className={`flex justify-center items-center`}>
<div
ref={divRef}
className={`bg-yellow-300 h-[8.6vw] w-[15vw]`}
onMouseOver={cardHovered}
>
<p>{props.num}</p>
<div className={`${classes}`} onMouseLeave={cardUnhovered}></div>
</div>
</div>
);
}
export default List;
The div that appears on hover is supposed to be positioned dynamically with respect to the hovered div but that doesnt happen when the flexbox is scrolled in x axis. how can i achieve this?
With tailwind CSS, you can not compute className strings dynamically, such as in
left-[${posX}px].Instead, you should add the
relativeposition to the parent (Card) className, so you can then specify the position of the child element (the bigger cover div) in terms of coordinates relative to the parent div's position -className = "absolute top-0 left-0"will position the cover element directly above the card, wherever it is. CSS will keep both elements positions in sync, so it would not be necessary to figure out the parent div's position programmatically anymore.