Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  • using display: none and setting display: inline on :before, 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...