csspseudo-element

In CSS use "display:none" on the element, but keep its ":after"


Is it possible to not display an element, as with display:none, but continue to display the :before and/or :after?

I tried

#myspan       {display:none}
#myspan:after {display:inline; content:"*"}

but that didn't work. I'm trying to have CSS replace the content of a span with an asterisk, without introducing jQuery.


Solution

  • No, it is not possible.

    Pseudo elements are rendered like children:

    <span id="myspan">whatever<after></span>
    

    And display:none hides the element including all children.

    EDIT 1

    JavaScript is your best option in my opinion. Even without jQuery changing text is not hard:

    document.getElementById("myspan").innerHTML = "*";ā€‹
    

    Demo

    EDIT 2

    However, if you really want to do it with CSS, you can use negative text-indent to hide the text and relative positioning to show the asterisk:

    #myspan {    
        text-indent: -9999px;
        display: block;
    }
    
    #myspan:before {
        content: '*';
        position: absolute;
        top: 0;
        left: 9999px;
    }
    

    Demo

    ā€‹