knitevision
knitevision

Reputation: 3143

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

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.

Upvotes: 40

Views: 15709

Answers (12)

ShortFuse
ShortFuse

Reputation: 6804

This may or may not work for you, but this is how I achieve it with pure CSS. The only caveat is the dependence of focus-within which isn't supported by IE or Edge.

.parent {
  transition: background-color;
}
.parent:active:not(:focus-within) {
  background-color: red;      
  transition-delay: 1ms; // Delay one cycle to allow child to focus 
}

What's going on here is, the parent element will get the active state, as will the child that gets clicked. The only difference is that the focus will apply to the child element, but only on the next cycle. To circumvent any animations from while in this 2 step process, apply a 1ms delay. The next cycle, the element will be active, but the focus will be applied to the child. Thus, the parent will not apply the transition. I would imagine animation delay: 1ms would work the same way.

Another alternative is to give the item a tabindex=-1 attribute and use

.parent {
  transition: background-color;
}
.parent:active:focus {
  background-color: red;      
}

The only issue with this is the fact it may change keyboard navigation behavior and relies on some HTML as well. If you do want keyboard navigation use tabindex=0 or any value besides -1. But there's no JS used.

There are some nice polyfills for focus-within that you can use for IE/Edge but that would go outside "CSS Only".

But, we can put both of them together to create this:

.parent {
  transition: background-color;
}

.parent[tabindex]:active:focus {
  background-color: red;
}

.parent:active:not(:focus):not(:focus-within) {
  background-color: red;
  transition-delay: 1ms;
}

This works on IE11, Edge, and Chrome.

http://jsfiddle.net/s0at4w4b/42/

Upvotes: 3

Oriol
Oriol

Reputation: 288230

I don't think :has pseudo-class will ever be available in stylesheets. If browsers finally decide to implement it, it will probably be only for JS APIs like querySelector.

However, I have much more hopes for :focus-within, which seems much simpler to implement.

#parent:active:not(:focus-within) {
  background-color: red;
}

Of course, it will only prevent :active from being applied to #parent when clicking a focusable element like a button. You can make other elements focusable by adding tabindex = "-1"

Sadly, :focus-within is not widely supported, but you can use a JS polyfill.

#parent {
  border: 1px solid black;
  width: 300px;
  height: 300px;
}
#parent:active:not(.focus-within) {
  background-color: red;
}
<script src="https://gist.githubusercontent.com/aFarkas/a7e0d85450f323d5e164/raw/"></script>
<div id="parent">
  <button>Click me</button>
  <p tabindex="-1">Or me</p>
</div>

Github does not allow hotlinking, so the snippet above might not work unless you copy the polyfill to your server and use it.

Upvotes: 6

AsimRazaKhan
AsimRazaKhan

Reputation: 2202

CSS pseudo-elements are incredibly useful -- they allow us to create CSS triangles for tooltips and perform a number of other simple tasks while preventing the need for additional HTML elements. To this point, these pseudo-element CSS properties have been unreachable by JavaScript but now there's a method for getting them!

Check this:

http://davidwalsh.name/pseudo-element

http://davidwalsh.name/ways-css-javascript-interact

Upvotes: 0

Vivek Athalye
Vivek Athalye

Reputation: 2979

There doesn't seem to any CSS way to handle this case. (not sure about CSS4, the way Amit has suggested.) So here is JQuery way.

The idea is you handle mousedown and mouseup events at 3 levels:

  1. the parent div
  2. the button where you don't want the active state propagated to parent div (".btn1" in the example below)
  3. any other children except the button in second condition. (".btn2" in the example below)

JS Fiddle

HTML:

<div>
  <button class="btn1">Qlick me1</button>
  <button class="btn2">Qlick me2</button>
</div>

JQuery:

$(function(){
    $('div').each(function(e){
        $(this).mousedown(function(e){
            $(this).addClass("activeClass");
        }).mouseup(function(e){
            $(this).removeClass("activeClass");
        });
    });
    $('div .btn1').each(function(e){
        $(this).mousedown(function(e){
            e.stopPropagation();
        }).mouseup(function(e){
            e.stopPropagation();
        });
    });
    $('div :not(.btn1)').each(function(e){
        $(this).mousedown(function(e){
            $(this).parent().addClass("activeClass");
        }).mouseup(function(e){
            $(this).parent().removeClass("activeClass");
        });
    });
});

CSS:

div {
  width: 200px;
  height: 200px;
  background-color: #eee;
  border: 1px solid black;
}
.activeClass {
  background-color: red;
}

Upvotes: 0

Rene van der Lende
Rene van der Lende

Reputation: 5281

Instead of div:active {...} you should code div:active:not(:hover) {...} and the background-color stays untouched.

(old snippet removed)

UPDATE

To keep the main div behaviour intact and a more generic approach I usually create several layers.

Check the snippet below, toggling to green is just to prove that it works while position and abolute are just quick and dirty for now:

#layer-data {
  width: 200px;
  height: 200px;
  background-color: #eee;
  border: 1px solid black;
}
#layer-data:active {
  background-color: red
}
#layer-btns:active {
  background-color: green
}
#layer-btns {
  z-index: 1;
  position: absolute;
  top: 1px;
  left: 1px;
  background: transparent;
  padding: 5px;
  width: auto;
  height: auto
}
#layer-data {
  z-index: 0;
  position: absolute;
  top: 0;
  left: 0;
  text-align: center;
  line-height: 200px
}
<div id="layer-btns">
  <button>Qlick me</button>
  <br/>
  <button>Qlick me too</button>
  <br/>
  <button>Qlick me three</button>
</div>

<div id="layer-data">
  some data-layer
</div>

Upvotes: 0

Albert Navasardyan
Albert Navasardyan

Reputation: 11

The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it. On systems with more than one mouse button, :active applies only to the primary or primary activation button (typically the "left" mouse button), and any aliases thereof.

There may be document language or implementation specific limits on which elements can become :active. For example, [HTML5] defines a list of activatable elements.

The parent of an element that matches :active also matches :active. So there,s no way

Upvotes: 0

becky1990
becky1990

Reputation: 161

try this

html:

<div class="current" id="current">
  <button id="btnclick" >Qlick me</button>
</div>

css script:

div {
  width: 200px;
  height: 200px;
  background-color: #eee;
  border: 1px solid black;
}
.current_active{
  background-color: red;
}

jquery:

$("#btnclick").click(function(){
    $("#current").toggleClass("current_active");
});

JSFiddle

ps: include the jquery library file

Upvotes: 0

Harry Robbins
Harry Robbins

Reputation: 549

As far as I know, the the active state will bubble up. So all parent nodes will have an active state.

Therefore, I don't now of a pure CSS solution. You can avoid a javascript solution (which I assume is what you're really after), by altering the markup so that the div that has an active state is no longer a parent of the button. You can make them siblings, for example.

The CSS part of that solution is then fixing the layout so it appears the same now that they are sibilings as what it did when they were parent>child.

Without seeing a fiddle of what you're working with, I can't offer you a more specific solution I'm afraid.

Upvotes: 0

Alfred Xing
Alfred Xing

Reputation: 4632

Perhaps the simplest way of achieving what you probably really want to do is to put not put the button inside the div you don't want activated.

Here, you have a container div, which contains a background div (the equivalent of the parent div in your original example). The background div has an active state separate from the button's.

.container {
  position: relative;
  width: 200px;
  height: 200px;
}
.background {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 1px solid black;
  background-color: #eee;
}
.background:active {
  background-color: red;
}
button {
  position: relative;
}
<div class="container">
  <div class="background"></div>
  <button>Click me!</button>
</div>

Upvotes: 4

MMachinegun
MMachinegun

Reputation: 3074

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.

Upvotes: 5

indubitablee
indubitablee

Reputation: 8206

here's a jquery solution instead of using the css pseudo class :active

$(document).ready(function() {
    $('button').mousedown(function(e){
        e.stopPropagation();
        console.log('i got clicked');
    });

    $('div').mousedown(function(e){
        $('div').css('background', 'red')
    }).mouseup(function(e){
        $('div').css('background', '#eee')
    });
    $(document).mouseup(function(e){
        $('div').css('background', '#eee')
    });
});
div {
  width: 200px;
  height: 200px;
  background-color: #eee;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button>Qlick me</button>
</div>

Upvotes: 0

Amit
Amit

Reputation: 46323

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.

Upvotes: 21

Related Questions