Skip to content Skip to sidebar Skip to footer

Is There A CSS Alternative To JS Click, (as :hover Is An Alternative Mouseover / Mouseout)?

Update: Thanks to explanations by Crowes and Boltclock below, I now have a clearer understanding that CSS pseudo-classes are explicitly stative (ie. describing an element's state i

Solution 1:

Is there a minimum effort pure CSS replacement for javascript's onclick?

Yes, there is a straightforward way to implement onclick behaviour using CSS alone.

Two steps:

  1. Add tabindex="0" to the element which requires the onclick behaviour
  2. Use the :focus pseudo-element to activate the onclick behaviour

Example:

p {
width: 100px;
height: 100px;
margin: 0;
line-height: 100px;
font-size: 16px;
text-align:center;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
font-weight: bold;
cursor: pointer;
transform: rotateY(0deg);
transition:
    width 1s ease-out,
    font-size 1s ease-out,
    line-height 2s ease-out,
    height 1s ease-out 1s,
    transform 1s ease-out 2s;
}

p::after {
content:' Me';
}

p:focus {
width: 300px;
height: 200px;
line-height: 200px;
font-size: 36px;
transform: rotateY(360deg);
}

p:focus::after {
content:' Elsewhere';
}
<p tabindex="0">Click</p>

Post a Comment for "Is There A CSS Alternative To JS Click, (as :hover Is An Alternative Mouseover / Mouseout)?"