Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Prevent parent element getting :active pseudoclass when child element is clicked

Tags:

html

css

JSFiddle

When you click the button, you see that :active pseudoclass is triggered for the parent div. Is there a pure CSS (or some JS library) way of :active pseudoclass not toggling on button click?

I tried z-index, position: absolute & fixed and no success.

like image 405
knitevision Avatar asked Oct 13 '15 23:10

knitevision


People also ask

How do you style the parent element when hovering a child element?

The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!

How do I apply CSS to child element based on parent?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors.

What is parent and child element in CSS?

A parent is an element that is directly above and connected to an element in the document tree. In the diagram below, the <div> is a parent to the <ul>. A child is an element that is directly below and connected to an element in the document tree.


2 Answers

From the spec:

Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.

That means it's implementation dependent. If an implementation chose to act this way (as current browsers obviously do), there's nothing in the standard that can change that.

With CSS4, you might be able to do:

.parent:active:not(:has(:active)) {
   color: red;
}

but that is neither available nor finalized yet.

like image 66
Amit Avatar answered Oct 08 '22 19:10

Amit


If you really want to solve this with CSS only:

If your button is active, add a :before-pseudo-element and with position: absolute; give the :before the same background as the parents.

button:active::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #eee;
    z-index: -1;
}

Now all that is needed is that the parent is :

position: relative;
z-index: 0;

Have a look: http://jsfiddle.net/s0at4w4b/4/

This does not solve the underlying issue, but is a solution for your current problem.

like image 5
MMachinegun Avatar answered Oct 08 '22 18:10

MMachinegun