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