有没有办法隐藏元素的内容,但保持其 :before
内容可见?假设我有以下代码:
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
,但两者仍处于隐藏状态宽度:0;溢出:隐藏
;,但随后似乎添加了额外的空间(?)text-indent: -....px
,但是display: none
and setting display: inline
on :before
, but both are still hidden width: 0; overflow: hidden
;, but then additional space seems to be added (?) text-indent: -....px
, but
关于我如何做到这一点的任何其他想法?
Any other ideas as to how I might do this?
您可以使用 visibility: hidden
,但使用此解决方案,隐藏的内容仍会占用空间.如果这对你来说不重要,你会这样做:
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;
}
<小时>
另一种解决方案是将 span to zero* 的 font-size
设置为一个非常小的值.这种方法的优点:隐藏的内容不会占用任何空间.缺点::before
内容的字体大小不能使用 em 或 % 等相对单位.
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,您现在可以使用 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 生成的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!