How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

.active:active {
  color: red;
}
.focus:focus {
  color: red;
}
:target {
  color: red;
}
<button class="active">Active</button>
<button class="focus">Focus</button>
<a href="#target1" id='target1' class="target">Target 1</a>
<a href="#target2" id='target2' class="target">Target 2</a>
<a href="#target3" id='target3' class="target">Target 3</a>

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

$('button').on('click', function(){
    $('button').removeClass('selected');
    $(this).addClass('selected');
});
button.selected{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Item</button><button>Item</button><button>Item</button>
  

Leave a Comment