問題描述
有沒有辦法隱藏元素的內(nèi)容,但保持其 :before
內(nèi)容可見?假設我有以下代碼:
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?
}
我試過了:
- 使用
display: none
并在:before
上設置display: inline
,但兩者仍處于隱藏狀態(tài) - 使用
寬度:0;溢出:隱藏
;,但隨后似乎添加了額外的空間(?) - 使用color: transparent;,但是當然span的內(nèi)容還是占空間
- 使用
text-indent: -....px
,但是
- using
display: none
and settingdisplay: 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
- 搜索引擎不贊成這一點,并且
- 它似乎不適用于 span 元素(?)
關于我如何做到這一點的任何其他想法?
Any other ideas as to how I might do this?
推薦答案
清潔解決方案
您可以使用 visibility: hidden
,但使用此解決方案,隱藏的內(nèi)容仍會占用空間.如果這對你來說不重要,你會這樣做:
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 替代解決方案
另一種解決方案是將 span to zero* 的 font-size
設置為一個非常小的值.這種方法的優(yōu)點:隱藏的內(nèi)容不會占用任何空間.缺點::before
內(nèi)容的字體大小不能使用 em 或 % 等相對單位.
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;
}
jsfiddle 示例.
更新(2015 年 5 月 4 日):使用 CSS3,您現(xiàn)在可以使用 rem
(根 EM)單元來維護 中的相對字體大小:before
元素.(瀏覽器支持.)
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.)
*此帖子的先前版本建議將字體大小設置為零.但是,這在某些瀏覽器中無法正常工作,因為 CSS 沒有定義預期的行為 當字體大小設置為零時.為了跨瀏覽器的兼容性,請使用上面提到的小字體.
*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.
這篇關于隱藏元素,但顯示 CSS 生成的內(nèi)容的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!