Sergio Estrada Sergio Estrada - 5 months ago 15
CSS Question

How do I make pseudo element :before stay active?

I'm currently struggling to make my psuedo element :before stay active when clicked.

I've made a small demo of what I have here:
https://jsfiddle.net/ud8p2nak/1/

I want it to stay active when you're on the current page, so if I'm on the accounts page I want my pseudo element to stay active on the Accounts page. I've tried with :active but that doesn't stay active fully. I'd appreciate the help, thank you.

<div class="side_col">

<a href="#">
<div class="side_link">Accounts
</div>
</a>
<a href="#">
<div class="side_link">Newsletter
</div>
</a>
<a href="#">
<div class="side_link">Operator
</div>
</a>
<a href="#">
<div class="side_link">Invoice
</div>
</a>




.side_col {
float: left;
width: 20%;
height: 100%;
background-color: #343A47;
}

.side_link:before {
float: left;
content: "";
display: inline-block;
height: 100%;
width: 7px;
background-color: #343A47;
}

.side_link:active::before {
background-color: #24BDE9;
}

.side_link {
text-align: left;
line-height: 50px;
width: 100%;
height: 50px;
background: #343A47;
color: #fff;
font-weight: 500;
}

.side_link:hover {
background-color: #2b303b;
}

.side_link_active {
background-color: #2b303b;
}

Answer

UPDATE

OP asked if it was possible to use :target with an additional <a> wrapped around it. Yes it is, see this test and click the last link named 'Invoice'.

FIDDLE

A CSS solution is using :target pseudo-class. It's easy:

  1. Assign an id to the element you intend to change states (on, off, active, inactive, etc.), which will be refered to as the target.
  2. Next, make an <a>nchor and assign it's href value to the target's id preceded by a # hashmark (ex. <a href='#idOfTarget'>LINK</a>).
  3. Lastly, create a CSS ruleset with the target and :target pseudo-class (ex. #idOfTarget:target { color: red; }.

SNIPPET

.side_col {
  float: left;
  width: 20%;
  height: 100%;
  background-color: #343A47;
}
.side_link:before {
  float: left;
  content: "";
  display: inline-block;
  height: 100%;
  width: 7px;
  background-color: #343A47;
}
#sl1:target:before,
#sl2:target:before,
#sl3:target:before,
#sl4:target:before {
  background-color: #24BDE9;
}
.side_link {
  text-align: left;
  line-height: 50px;
  width: 100%;
  height: 50px;
  background: #343A47;
  color: #fff;
  font-weight: 500;
}
.side_link:hover {
  background-color: #2b303b;
}
<div class="side_col">

  <a href="#sl1">
    <div id="sl1" class="side_link">Accounts
    </div>
  </a>
  <a href="#sl2">
    <div id="sl2" class="side_link">Newsletter
    </div>
  </a>
  <a href="#sl3">
    <div id="sl3" class="side_link">Operator
    </div>
  </a>
  <a href="#sl4">
    <div id="sl4" class="side_link">Invoice
    </div>
  </a>

</div>

Comments