1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【CSS】ホバー時に外から内に囲まれるように表示される罫線アニメーション

Posted at

■概要
CSSの::beforeと::after疑似要素を使用して、リンクにホバーした際に罫線が動的に表示されるエフェクトを実装する方法を紹介します。


■具体的に
リンクの周りに初期状態で表示される罫線「」が、ユーザーがリンクにマウスを合わせたときに外側から内側に向かって拡大するアニメーション効果についてのコードと解説をしています。


■実装のメリット
このエフェクトを用いることで、ウェブサイトのUIに洗練された視覚的魅力を加えることができます。


■実際の挙動

screenshot_05.png

screenshot_06.png


■コード

HTML
<div class="readMore">
    <a href="#">Read More</a>
</div>
CSS

#about .readMore a {
  position: relative;    /* 相対指定 */
  display: inline-block; 
  font-size: 0.875rem;   /* フォントサイズ */
  padding: 18px 45px;    /* 内側の余白 */
  color: #000;           /* 文字色 */
}

/* ::beforeと::after疑似要素に共通するスタイル */
#about .readMore a::before, 
#about .readMore a::after {  
  border: 2px solid #E03131;
  position: absolute;               /* 絶対指定 */
  content: "";                      /* コンテンツの内容を空に */  
  transition: all 0.3s ease-in-out; /* 徐々に加速 */
}

/* ::before疑似要素のスタイル「左上括弧」 */
#about .readMore a::before {  
  border-width: 2px 0 0 2px; /* 上と左の境界線のみ表示 */
  top: 0;                    /* 要素の上端からの位置 */
  left: 0;                   /* 要素の左端からの位置 */
  width: 30px;               /* 幅を30pxに設定 */
  height: 25px;              /* 高さを25pxに設定 */
}

/* ::after疑似要素のスタイル「右下括弧」 */
#about .readMore a::after {  
  border-width: 0 2px 2px 0; /* 下と右の境界線のみ表示 */
  bottom: 0;                 /* 要素の下端からの位置 */
  right: 0;                  /* 要素の右端からの位置 */
  width: 30px;               /* 幅を30pxに設定 */
  height: 25px;              /* 高さを25pxに設定 */
}

/* ホバー時の::beforeと::after疑似要素のスタイル */
#about .readMore a:hover::before,
#about .readMore a:hover::after {  
  width: 100%;               /* 幅を要素全体に拡大 */
  height: 100%;              /* 高さを要素全体に拡大 */
}

■コードの解説
1、aタグに相対指定
2、疑似要素beforeとafterに共通するスタイルを充てます、具体的には絶対指定とボーダーの太さと色、そしてアニメーションの速度です
3、疑似要素after
border-widthを使い括弧の左上を作成します(「 )
上と左を2px、右と下は0に設定することで実現します。
3、疑似要素before
こちらもafterと同じ考え方で右下括弧( 」)を表示させます。
4、疑似要素にカーソルが触れた時にwidthとheightを100%にして周りの罫線を全て表示させます。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?