6

I have the following case: (styling is done in SASS and unnecessary stylings are omitted.)

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }
}

This creates a bar on top of the application's menu bar. In certain cases this bar has to be removed. I have read questions like these, but with no success. What would be the best way to remove this bar added by the ::before selector?

Community
  • 1
  • 1
Jan Swart
  • 6,137
  • 8
  • 32
  • 41

3 Answers3

8

Only CSS can remove pseudo element, so you need to have an other class that display:none; the before. First declare that class in the CSS :

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }

  &.no-before::before{
    display:none;
  }
}

Then, when you want to remove it :

$('.header').addClass('no-before'); //Remove before
$('.header').removeClass('no-before'); //Re-add before
Karl-André Gagnon
  • 33,269
  • 5
  • 49
  • 72
7

The usual way is to create a more specific rule that applies to the element(s) in question (or a later rule with the same specificity), and specify display: none to hide the pseudo in that case.

For example: Here, I want to have an X in front of <span class="foo">, but not if they're in .header:

span.foo::before {
  content: 'X ';
}
.header span.foo::before {
  display: none;
}
<div>
  These have the X:
  <span class="foo">span.foo 1</span>
  <span class="foo">span.foo 2</span>
  <span class="foo">span.foo 3</span>
</div>
<div class="header">
  These don't:
  <span class="foo">span.foo 4</span>
  <span class="foo">span.foo 5</span>
  <span class="foo">span.foo 6</span>
</div>
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
3

If you are manipulating the DOM by using JavaScript, you can add a class name - for instance .remove-bar - to the element having .header in order to remove the pseudo-element (generated content):

.remove-bar {
    &::before { content: none; }
}

Also make sure that it is placed after the previous styles, or use a more specific selector if needed.

Hashem Qolami
  • 93,110
  • 25
  • 145
  • 156