Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an element added by ::before pseudo selector

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?

like image 319
Jan Swart Avatar asked Feb 19 '15 13:02

Jan Swart


People also ask

When would you use the :: before or :: after pseudo-element in your CSS?

The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.

What is pseudo-element explain with Example A :: before?

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.

What is before pseudo selector?

The :before selector is a pseudo-class that allows you to add content before a selected element. This element is an inline element.

What is before and after pseudo selector?

The ::before and ::after pseudo-elements in CSS allows you to insert content onto a page without it needing to be in the HTML.


2 Answers

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
like image 129
Karl-André Gagnon Avatar answered Sep 28 '22 02:09

Karl-André Gagnon


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>
like image 25
T.J. Crowder Avatar answered Sep 28 '22 02:09

T.J. Crowder