隐藏元素,但显示CSS生成的内容 [英] Hide element, but show CSS generated content

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

问题描述

是否有隐藏元素内容的方法,但保留其:之前内容可见?
说我有以下代码:

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 并设置 display:inline $ c>:before ,但两者仍然隐藏

  • 使用 width:0; overflow:hidden ;但是后来额外的空间似乎被添加了(?)

  • 使用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元素(?)

li>

有关我如何做到的任何其他想法吗?

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;
}






h1>

另一个解决方案是将span font-size 设置为零 *一个非常小的值。这种方法的优点:隐藏的内容不会占用任何空间。缺点:您将无法使用相对单位,例如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;
}

Example on jsfiddle.

更新(2015年5月4日):使用CSS3,您现在可以使用 rem (Root 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没有定义期望的行为当font-size设置为零时。对于跨浏览器兼容性,请使用如上所述的小字体大小。

*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生成的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆