htmlcsscss-selectors

Hide element, but show CSS generated content


Is there a way of hiding an element's contents, but keep its :before content visible? Say I have the following code:

HTML:

<span class="addbefore hidetext">You are here</span>

CSS:

.addbefore:before {
    content: "Show this";
}
.hidetext {
    // What do I do here to hide the content without hiding the :before content?
}

I've tried:

Any other ideas as to how I might do this?


Solution

  • Clean Solution

    You could use visibility: hidden, but with this solution, the hidden content will still take up space. If this doesn't matter to you, this is how you would do it:

    span {
        visibility: hidden;
    }
    
    span:before {
        visibility: visible;
    }
    

    Hackish Alternative Solution

    Another solution would be to set the font-size of the span to zero* to a really small value. Advantage of this method: The hidden content won't take up any space. Drawback: You won't be able to use relative units like em or % for the font-size of the :before content.

    span:before {
        content: "Lorem ";
        font-size: 16px;
        font-size: 1rem; /* Maintain relative font-size in browsers that support it */
        letter-spacing: normal;
        color: #000;
    }
    
    span {
        font-size: 1px;
        letter-spacing: -1px;
        color: transparent;
    }
    

    Example on jsfiddle.

    Update (May 4, 2015): With CSS3, you can now use the rem (Root EM) unit to maintain relative font-sizes in the :before element. (Browser support.)


    *A previous version of this post suggested setting the font size to zero. However, this does not work as desired in some browsers, because CSS does not define what behavior is expected when the font-size is set to zero. For cross-browser compatibility, use a small font size like mentioned above.