2024-01-11 10:00:02

使用css隐藏文本

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

<h1>My Website Title Here</h1>

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


当前回答

最好的答案适用于短文本,但如果文本换行,它只会显示在图像中。

一种方法是用jquery处理程序捕获错误。尝试加载一个图像,如果失败,它会抛出一个错误。

$('#logo img').error(function(){
    $('#logo').html('<h1>My Website Title Here</h1>');
});

参见SAMPLE CODE

其他回答

这是一种方法:

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

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

要在html中隐藏文本,使用css中的text-indent属性

.classname {
 text-indent: -9999px;
 white-space: nowrap; 
}

/*对于动态文本,您需要添加空白,这样您应用的CSS将不会打扰。Nowrap意味着文本永远不会换行到下一行,文本将继续在同一行上,直到遇到<br>标记

只需添加font-size: 0;到包含文本的元素。

.hidden {font-size: 0;} 字体大小:0;隐藏文本。<span class="hidden">你看不到我:)</span>

这对我来说适用于span(敲除验证)。

<span class="validationMessage">This field is required.</span>

.validationMessage {
    background-image: url('images/exclamation.png');
    background-repeat: no-repeat;
    margin-left: 5px;
    width: 16px;
    height: 16px;
    vertical-align: top;

    /* Hide the text. */
    display: inline-block;
    overflow: hidden;
    font-size: 0px;
}