2024-01-11 10:00:02

使用css隐藏文本

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

<h1>My Website Title Here</h1>

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


当前回答

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

其他回答

隐藏文本与可访问性:

除了其他答案之外,还有另一种有用的隐藏文本的方法。

此方法有效地隐藏了文本,但允许它对屏幕阅读器保持可见。如果需要考虑可访问性,可以考虑这个选项。

.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
}

值得指出的是,这个类目前在Bootstrap 3中使用。


如果你对无障碍阅读感兴趣:

无障碍网页计划(WAI) MDN易访问性文档

使用条件标签不同的浏览器和使用css你必须放置 高度:0px,宽度:0px,你还必须放置字体大小:0px。

这是一种方法:

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

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

我通常使用:

span.hide
{
  position:fixed;
  right:-5000px;
}