Change the color of div when user clicks over it
You can simply use :focus
Pseudo class with Tabindex
.
But if you focus any other things, then the background style of tabs will be lost :(
.tabs>a>p:focus{
background-color:gray !important;
display:inline-block;
color:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-2 tabs" >
<a href="#">
<p tabindex="1"> First </p>
</a>
</div>
<div class="col-md-2 tabs" >
<a href="#">
<p tabindex="2"> Second </p>
</a>
</div>
<div class="col-md-2 tabs" >
<a href="#">
<p tabindex="3"> Third </p>
</a>
</div>
$(".tabs").on("click", function(e){
e.preventDefault();
$(".tabs.active").removeClass("active");
$(this).addClass("active");
});//
$(".tabs").eq(0).trigger("click");
.tabs.active a
{
display: block;
background: black;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="col-md-2 tabs">
<a href="#">
<p> First </p>
</a>
</div>
<div class="col-md-2 tabs">
<a href="#">
<p> Second </p>
</a>
</div>
<div class="col-md-2 tabs">
<a href="#">
<p> Third </p>
</a>
</div>
It is not directly possible to catch a click event with CSS, but there does exist a couple of "hacks". One of them is to use a checkbox:
div {
width: 100px;
height: 50px;
padding: 4px;
background-color: blue;
color: white;
border: 4px solid green;
}
input[type="checkbox"] {
display: none;
}
input[type="checkbox"] + label {
display: table;
margin: 20px;
}
input[type="checkbox"]:checked + label div {
background-color: red;
color: black;
}
<input type="checkbox" id="cb1">
<label for="cb1">
<div>
Div 1 - click me
</div>
</label>
<input type="checkbox" id="cb2">
<label for="cb2">
<div>
Div 2 - click me
</div>
</label>
As you see the divs are encased in labels which are bound to hidden checkboxes. When you click the label (or anything inside it) the checkbox state changes, and CSS is applied thus.
The selector input[type="checkbox"]:checked + label div
finds any checked checkbox, finds the direct sibling of type label
and the div
within. It is therefore required that the label comes directly after its companion checkbox in the html.
You should be able to modify this code to suit your needs.
UPDATE: In my previous version the label (and therefore the click registration bounds) extended to the left and right edges of the parent container (the body, in this case). By setting display: table;
on the label one avoids this while keeping the block behaviour. You can also use inline-block
if you want the divs on the same line.
With :target pseudo-class
.col-md-2:target {background-color: black;}
<div class="col-md-2 tabs" id="first">
<a href="#first">
<p> First </p>
</a>
</div>
<div class="col-md-2 tabs" id="second" >
<a href="#second">
<p> Second </p>
</a>
</div>
<div class="col-md-2 tabs" id="third">
<a href="#third">
<p> Third </p>
</a>
</div>