Overlap a div without using z-index
P粉124070451
2023-08-17 13:56:28
<p>I've run into a problem that I can't seem to solve, and I'm thinking of some CSS magic, but what's the best approach for this problem? </p>
<p>I have a progress bar component that has an ideal area and actual progress bar. When the progress bar overlaps the ideal area, I want to hide the ideal area as if it had a smaller z-value. I tried this and found that z-index does not work on statically positioned elements, how can I replicate this behavior? Here is the code for the component, which also uses tailwind for styling. </p>
<pre class="brush:php;toolbar:false;">import React, { useEffect, useState } from 'react';
type ProgressbarProps = {
value: number,
maxValue: number,
percentageCap: number,
idealZone: number
};
function Progressbar({ value, maxValue, percentageCap, idealZone }: ProgressbarProps) {
const [displayedPercentage, setDisplayedPercentage] = useState(0);
const idealZoneStart = 100 - idealZone/2;
const idealZoneEnd = 100 idealZone/2;
useEffect(() => {
const actualPercentage = (value / maxValue) * 100;
setDisplayedPercentage(Math.min(percentageCap, actualPercentage));
}, [value, maxValue]);
const progressBarColor =
displayedPercentage < idealZoneStart
? 'bg-orange-500'
: displayedPercentage > idealZoneEnd
? 'bg-red-500'
: 'bg-green-500';
const progressBarStyle = {
width: `${(displayedPercentage / percentageCap) * 100}%`,
};
const idealZoneStyle = {
left: `${(idealZoneStart / percentageCap) * 100}%`,
width: `${((idealZoneEnd - idealZoneStart) / percentageCap) * 100}%`,
};
return (
<div className="relative">
<div className={`h-4 rounded ${progressBarColor}`} style={progressBarStyle}></div>
<div className="absolute top-0 left-0 w-full h-4 bg-gray-200" style={idealZoneStyle}></div>
</div>
);
}
export default Progressbar;</pre>
I'm not sure if this answers your question, but try this:
CSS selectors and styles:
First define the necessary CSS selectors and style rules. Assuming your component container has class name
) to locate the desired area and apply styles to hide it to prevent progress Bar overlap:
.progressbar-container
, you can use adjacent sibling selector (Component implementation:
In your React component implementation, you can use the concept of the
.overlap
class to control the behavior of the ideal area and judge based on the overlap conditions:By conditionally applying the
.overlap
class on the component container based on the overlap condition, adjacent sibling selectors in CSS will hide the desired area when the progress bars overlap. When the conditions are not met, the ideal area will be displayed as expected.