Removing an element added by ::before pseudo selector

前端 未结 3 783
谎友^
谎友^ 2021-01-13 20:14

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

.header {
  ...
  &::before {
    ...
    position: absolute;         


        
相关标签:
3条回答
  • 2021-01-13 20:53

    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
    
    0 讨论(0)
  • 2021-01-13 20:58

    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>

    0 讨论(0)
  • 2021-01-13 20:58

    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.

    0 讨论(0)
提交回复
热议问题