隐藏元素,但显示 CSS 生成的内容

时间:2022-11-20
本文介绍了隐藏元素,但显示 CSS 生成的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法隐藏元素的内容,但保持其 :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;溢出:隐藏;,但随后似乎添加了额外的空间(?)
  • 使用color: transparent;,但是当然span的内容还是占空间
  • 使用 text-indent: -....px,但是
  • 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. 搜索引擎不赞成这一点,并且
  2. 它似乎不适用于 span 元素(?)

关于我如何做到这一点的任何其他想法?

Any other ideas as to how I might do this?

推荐答案

清洁解决方案

您可以使用 visibility: hidden,但使用此解决方案,隐藏的内容仍会占用空间.如果这对你来说不重要,你会这样做:

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 设置为一个非常小的值.这种方法的优点:隐藏的内容不会占用任何空间.缺点::before 内容的字体大小不能使用 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,您现在可以使用 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模板网!

上一篇:什么 CSS 选择器可以用来选择另一个 div 中的第一 下一篇:CSS3 的 :root 伪类和 html 有什么区别?

相关文章

最新文章