Blind
Blind

Reputation: 93

How to use active and before with CSS?

I would create an effect with CSS using pseudo-class ::before :active. I created an effect that if you click the element of p before, content before p changes. I thought that didn't work because before p can't be select.
This is my code, but doesn't work:

.container {
  background-color: #222;
  border-radius: 5px;
  width: 200px;
  display: block;
  margin: 0 auto;
}

.container > p {
  color: #fff;
  padding: 10px;
  text-align: center;
}

.container > p::before {
  content: 'ON';
}

p:active + p:before {
  content: 'OFF';
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container"><p></p></div>
</body>
</html>

Upvotes: 1

Views: 15622

Answers (2)

Asons
Asons

Reputation: 87191

Change this rule, p:active + p:before, to p:active:before

.container {
  background-color: #222;
  border-radius: 5px;
  width: 200px;
  display: block;
  margin: 0 auto;
}

.container > p {
  color: #fff;
  padding: 10px;
  text-align: center;
}

.container > p::before {
  content: 'ON';
}

p:active:before {
  content: 'OFF';
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container"><p></p></div>
</body>
</html>

Upvotes: 4

Quentin
Quentin

Reputation: 943185

p:active + p:before means The pseudo-element that appears before the paragraph which is immediately after the (other) paragraph which the mouse is pointing to while the mouse button is pressed.

Since you only have one paragraph, that can't ever match anything.

Perhaps you meant p:active:before?

.container {
  background-color: #222;
  border-radius: 5px;
  width: 200px;
  display: block;
  margin: 0 auto;
}

.container > p {
  color: #fff;
  padding: 10px;
  text-align: center;
}

.container > p::before {
  content: 'ON';
}

p:active:before {
  content: 'OFF';
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container"><p></p></div>
</body>
</html>

Upvotes: 8

Related Questions