LoginSignup
10
12

More than 5 years have passed since last update.

CSSで鏡文字を表現してみた。

Last updated at Posted at 2015-09-24

sample.png

もっと簡単な方法があるかも?


<p data-text="" id="text">Hello World!</p>


data-* カスタムデータ属性
詳しくはGlobal attributes - HTML | MDN

css

#text{
  position: relative;
  font-size: 5em;
  color: #fff;
  text-shadow: 3px 0 5px #eee;
}

#text:before{
  position: absolute;
  top: 1em;
  content: attr(data-text);
  color: inherit;
  opacity: 0.5;
  transform: rotateX(180deg);
}

javascript

var text = document.querySelector('#text');
text.setAttribute('data-text',text.textContent);

解説

:beforeのcontentに直接Hello World!と書けばいいのだが、(pタグの)テキストを編集したときにcontentのテキストも編集しないといけなくなる。

カスタムデータ属性を使うことで編集箇所が1箇所で済むようにした。

[流れ]

1.jsでテキスト要素を取得


var text = document.querySelector('#text');

2.テキスト要素の属性にdata-****(*は任意)を追加、値をtext.textContentとする


text.setAttribute('data-text',text.textContent);

3.CSSで:beforeのcontentに下記を追加する


content: attr(data-text);

これで文字を反転させれば鏡文字の完成!

ブラウザ

Chrome 45 , Firefox 41 , Safari 9 は動作確認済み。

10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12