Recently I was making some UI for a friend's project. We had this CSS button effect that works elsewhere but failed to work at the desired location. Upon troubleshooting, we discovered that if the parent element has a background defined, you can't control the z-index of the pseudo selection of any of its children. Wait for it, I have got some demo.
TL;DR
set background colour or image for a "DIV.parent
", create a "Div.child
" inside the "DIV.parent
". use CSS to modify the "::before"
" element of the "Div.child
" as follows; set position as absolute, content as an empty string, height:100% and width is best at 50% for example purposes, lastly, give it a background colour.
You will observe that the "::before"
" element is overlaying the actual element's content. Try to adjust the z-index of the "::before"
". You will also realize that the z-index works fine if we remove the background setting for "DIV.parent
".
Let's run through some code.
we begin with our markup then we move to CSS styles.
Our goal is to have a DIV where the background colour is defined on the pseudo-element(::before). For this to happen, we must make the DIV's position relative, then we set an absolute position for the pseudo-element. The pseudo-element also needs to be 100% height and any width greater than zero is fine. The absolute position here will force our pseudo-element to overlay the text. This is why we need to set a "z-index". The issue now is that the z-index is not giving desired effects. This was traced to the fact that the "parent" container had a background property defined.
Now to the CSS styles
Here in the style, we set the z-index as auto, to ensure that we can see what happens when the z-index is not set.
I am not sure what can be called a bug. I have only tried this on chrome browser (Version 92.0.4515.107 (Official Build) (64-bit)) so feel free to engage and let's see what happens at your own end when you test on all browsers. Perhaps you could find a better reason why this has to be so.
Cheers.
The resolution: if you have to use the pseudo-element for a similar function, ensure the parent container has no background property defined. Or better still, set your background property on the body tag.
Plot Twist: If you add background colour to the ".child" style, it becomes more messy and unusable.
This however has been solved and I am making a new article on how we got it solved.
Ill check this out
ReplyDeletethanks for visiting
ReplyDelete