【HTML】別窓アイコンの作り方【CSS】

どうも、くまだです。

ネタがなさ過ぎてやばいのですが、今回はよくある別窓アイコンの作り方というか、やりがちな失敗みたいなのを書いていきます。

別窓アイコンの作り方

よくあるやつですが、こんな感じです。

  <p class="c-commonText">てきすとテキスト<a href="#" target="_blank" rel="noopener noreferrer"> テキストの中の別窓リンク</a>テキスト</p>
  <p class="c-commonText">てきすとテキスト<a href="#"> テキストの中のリンク</a>テキスト</p>
.c-commonText {
  font-size: 16px;
}

.c-commonText a {
  color: red;
  text-decoration: underline;

}


.c-commonText a[target="_blank"] {
  position: relative;
  padding-right: 16px;
  margin-right: 4px;
  word-wrap: break-word;

}

.c-commonText a[target="_blank"]::before,
.c-commonText a[target="_blank"]::after {
  content: "";
  position: absolute;
  width: 10px;
  height: 10px;
  border-style: solid;
  border-color: red;
}

.c-commonText a[target="_blank"]::before {
  top: 50%;
  right: 3px;
  border-width: 1px;
  transform: translateY(-50%);
}

.c-commonText a[target="_blank"]::after {
  top: 50%;
  right: 0px;
  border-width: 0 1px 1px 0;
  transform: translateY(-2px);
}


別窓アイコン実装画面

別窓なので、通常のaタグに付かないように、aタグにtarget=”_blank”が付いているときだけ疑似要素で表示できるように設定します。

ただし、このやり方だとテキストが折り返したとき表示崩れます。

別窓アイコンのスタイル崩れ

こういう場合、自分だったら調整がめんどうなので、別窓アイコン自体は画像にしてしまいます…(この記事の元も子もないけど)

.c-commonText a[target="_blank"]::after {
  content: "";
  background: url(window.png) center / contain;
  width: 14px;
  height: 12px;
  display: inline-block;
  position: absolute;
  bottom: 6px;
}

別窓アイコン画像

こんな感じ。文中の中に別窓アイコンいれるような場合は、画像で対応するのが安全かもしれない…。

文中の中ではなく、例えば別窓アイコンが右端固定位置とかだったら、疑似要素でも対応できます。↓こういうやつ。

別窓アイコン 疑似要素

ここまで読んでくださりありがとうございました。

この記事を書いた人