Jon Gjengset Jon Gjengset - 1 year ago 79
CSS Question

Hide element, but show CSS generated content

Is there a way of hiding an element's contents, but keep its

content visible?
Say I have the following code:


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


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

I've tried:

  • using
    display: none
    and setting
    display: inline
    , but both are still hidden

  • using
    width: 0; overflow: hidden
    ;, but then additional space seems to be added (?)

  • using color: transparent;, but then, of course, the content of the span still takes up space

  • using
    text-indent: -....px
    , but

    1. this is frowned upon by search engines and

    2. it seems not to work for span elements (?)

Any other ideas as to how I might do this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download