Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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 は動作確認済み。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away