使用CSS隐藏文本,最佳实践?

时间:2012-10-08 14:07:34

标签: html css hide

假设我有这个元素用于显示网站徽标:

<div id="web-title">
  <a href="http://website.com" title="Website" rel="home">
    <span>Website Name</span>
  </a>
</div>

#blog-title将使用background:url(http://website.com/logohere.png)设置样式,但如何正确隐藏文字Website Name?如此处所示:Hide text using css或此处https://stackoverflow.com/a/2705328,我看到了隐藏文字的各种方法,例如:

#web-title span { text-indent: -9999px; }

#web-title span { font-size: -9999px; }

#web-title span { position: absolute; top: -9999px; left: -9999px; }

我也看到一些人将这三种方法结合起来。但实际上哪一个是有效隐藏文本的最佳做法?

12 个答案:

答案 0 :(得分:76)

实际上,最近出现了一种新技术。本文将回答您的问题:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

可访问,性能优于-99999px。

更新:由于@deathlock在评论区域中提及,上述修正的作者(Scott Kellum)建议使用transparent fonthttp://scottkellum.com/2013/10/25/the-new-kellum-method.html

答案 1 :(得分:15)

你可以简单地让它变得透明

{
   width: 20px;
   height: 20px;
   overflow: hidden; 
   color:transparent;
}

答案 2 :(得分:6)

你不能像这样使用display: none;

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

如果您担心保留空间

,如何玩可见性
.webname {
   visibility: hidden;
}

答案 3 :(得分:3)

大多数开发人员将采取的方式是:

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

.webname {
   display: none;
}

我曾经也这样做,直到我意识到你正在隐藏设备的内容。又名屏幕阅读器等。

通过传递:

#web-title span {text-indent: -9000em;}

确保文本仍然可读。

答案 4 :(得分:2)

将.hide-text类添加到包含文本

的范围
.hide-text{
display:none;
 }

或使文字透明

.hide-text{
 color:rgba(0,0,0,0);
 }

根据您的使用情况使用。

答案 5 :(得分:0)

如果你愿意在你的标记中容纳这个(就像你在提问时那样),我会选择jQuery UI在他们的CSS helpers中使用的任何内容:

.ui-helper-hidden-accessible { 
    position: absolute !important; 
    clip: rect(1px 1px 1px 1px); 
    clip: rect(1px,1px,1px,1px); 
}

如果您绝对拒绝为要隐藏在图像容器中的文本添加额外标记,则图像替换技术很好。

答案 6 :(得分:0)

Google(搜索机器人)需要的是同一内容应该在向用户提供时提供给机器人。缩进文本(任何文本)让机器人认为它是垃圾邮件,或者您向用户和机器人提供不同的内容。

最好的方法是直接将徽标用作锚标记内的图像。为图片添加“alt”。这对于机器人阅读和阅读来说是完美的。也有助于图像搜索。

直接来自马的嘴:http://www.youtube.com/watch?v=fBLvn_WkDJ4

答案 7 :(得分:0)

截至2015年9月,最常见的做法是使用以下CSS:

.sr-only{
    clip: rect(1px, 1px, 1px, 1px);
    height: 1px;
    overflow: hidden;
    position: absolute !important;
    width: 1px;
}

答案 8 :(得分:0)

我这样做:

.hidden-text {
  left: 100%;
  display: inline-block;
  position: fixed;
}

答案 9 :(得分:0)

另一种方式

let s = 3;
let counter = 1;

for(let i=0; i<s; i++) {
  let temp = [];
  for(let j=0; j<s; j++) {
    temp.push(counter++)
  }  
  console.log(temp.join(' '));
}

答案 10 :(得分:0)

它可能会起作用。

.hide-text {
    opacity:0;
    pointer-events:none;
    overflow:hidden;
}

答案 11 :(得分:-2)

我意识到这是一个老问题,但Bootstrap框架有一个内置类(仅限sr)来处理除屏幕阅读器之外的所有内容的隐藏文本:

<a href="/" class="navbar-brand"><span class="sr-only">Home</span></a>