2024-01-11 10:00:02

使用css隐藏文本

我有一个标签在我的html像这样:

<h1>My Website Title Here</h1>

使用css我想替换文字与我的实际标志。我已经得到的标志没有问题,通过调整标签和把背景图像通过css。然而,我不知道如何去掉这段文字。我以前见过,基本上就是把文字从屏幕上推开。问题是我不记得在哪里看到的。


当前回答

你可以使用CSS的background-image属性和z-index来确保图像保持在文本的前面。

其他回答

如果只是为了让元素内部的文本不可见,可以使用rgba值将color属性设置为不透明度为0,例如color:rgba(0,0,0,0);干净简单。

在CSS中,可以使用Content属性直接进行内容替换。

这似乎最常用于生成::before和::after伪元素,但也可用于替换现有HTML元素的内容。

对于最初的示例

<h1>My Website Title Here</h1>

这个CSS将用logo替换文本:

        h1 {
            content: url(mywebsitelogo.png);
            width: 100%;
        }

虽然在伪元素中,任何图像内容都不能调整大小(除非将其用作背景图像),但对于替换的内容则不是这样。

默认情况下,图像将显示其实际大小,并在必要时展开容器,就像它包含一个实际的<img>元素一样。

在本例中,width: 100%用于将标志图像贴合到全宽度。如果需要将图像缩小到合适的位置,但如果容器比图像大,则永远不要展开,那么可以使用max-width: 100%来代替。

根据MDN的说法,目前唯一不支持CSS内容替换的普通浏览器是Internet Explorer。

一个对我有效的解决方案:

HTML

<div class="website_title"><span>My Website Title Here</span></div>

CSS

.website_title {
    background-image: url('../images/home.png');
    background-repeat: no-repeat;
    height: 18px;
    width: 16px;
}

.website_title span {
    visibility: hidden;
}

为什么不用:

<li><a href="#">bla</a></li>

a {
    opacity: 0.0;
    font-size: 1px;
}

li {
    background-image: url('test.jpg');
}

如果你没有任何span或div元素,它可以完美地用于链接。

这是一种方法:

h1 {
    text-indent: -9999px;                 /* sends the text off-screen */
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width: 600px;
    white-space: nowrap;            /* because only the first line is indented */
}

h1 a {
    outline: none;  /* prevents dotted line when link is active */
}

下面是另一种隐藏文本的方法,同时避免浏览器创建的巨大的9999像素框:

h1 {
    background-image: url(/the_img.png);  /* shows image */
    height: 100px;                        /* be sure to set height & width */
    width:  600px;

    /* Hide the text. */
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}