2024-01-11 10:00:02

使用css隐藏文本

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

<h1>My Website Title Here</h1>

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


当前回答

不要使用{display:none;它使内容无法访问。您希望屏幕阅读器看到您的内容,并通过将文本替换为图像(如徽标)来视觉化它。text-indent: -999px;或者类似的方法,文本仍然在那里——只是没有视觉上的存在。使用display:none,文本就消失了。

其他回答

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

这对我来说适用于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;
}
h1{
   background:url("../images/logo.png") no-repeat;
   height:180px;
   width:200px;
   display:inline-block;
   font-size:0px !important;
   text-intent:-9999999px !important;
   color:transparent !important;
 }

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

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

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

参见SAMPLE CODE

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

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

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