text-indent: -9999px; ってなんぞや

投稿日: 2022/11/20
更新日: 2022/11/20
シェア:

URL copied!


概要

文字が書いてあるのに表示されていなく、画像に置き換わっているところを発見。どうやっているのかと思いきや。。。

画面外に飛ばしてた。。

試しに text-indent でずらしてみた。

<style>
  .sample {
    width: 50%;
  }
  .sample p {
    background: url("/static/img/fulldict.png") no-repeat left/20px;
    font-size: 20px;
  }
</style>
<div style="background-color: cyan" class="sample">
  <p style="text-indent: 0px;">full dict</p>
  <p style="text-indent: -9px;">full dict</p>
  <p style="text-indent: -9999px;">full dict</p>
</div>

画面外にサヨナラしていました。

sample

full dict

full dict

full dict

今はおすすめではないらしい

そもそも画面外に 9999px の領域を使うことになるのでそこまでパフォーマンスが良くないそうだ。
それに加えて Google にSEOスパムだと思われる可能性 があるそうだ。それは困る。隠しテキストに該当するのか。
そこで紹介されていた方法としては

.bg-image {
  background-image: url("/static/img/fulldict.png");
  overflow: hidden;
  text-indent: 100%;
  white-space: nowrap;
}

これを分解して何をしているか確認。

<style>
  .sample2 {
    width: 50%;
  }
  .sample2 p {
    font-size: 20px;
    background: url("/static/img/fulldict.png") no-repeat left/20px;
  }
</style>
<div style="background-color: cyan" class="sample2">
  <p style="text-indent: 90%;">full dict</p>
  <p style="text-indent: 100%;">full dict</p>
  <p style="text-indent: 100%; white-space: nowrap;">full dict</p>
  <p style="overflow: hidden; text-indent: 100%; white-space: nowrap;">full dict</p>
</div>

インデントで領域外に文字を出して、折り返しをさせなくして、領域外のものを非表示にしていたんですね。

sample

full dict

full dict

full dict

full dict

そもそも img タグの alt 属性ではダメなの?

私は今までこのテクニックを知らなかったので、img タグの alt 属性に書いておけばおりました。これも正攻法で問題ないようです。
ただ、alt 属性のテキストより通常のテキストの方が評価されやすいからそうやっているみたいでした。 ちゃんちゃん。

参考