Fancy Hover Effect With Anchor Positioning
記事は上記記事を意訳したものです。
※当ブログでの翻訳記事は元サイト様に許可を得て掲載しています。
CSS Anchor Positioningを使用したCSSだけでできるナビゲーションのホバーエフェクトをご紹介します。
アニメーションする長方形を伴ったホバーエフェクト
<nav> <ul> <li><a href="#">Home</a></li> <li class="active"><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul> </nav>
ul { padding: 0; margin: 0; list-style: none; display: flex; gap: 1rem; font-size: 2.2rem; isolation: isolate; } ul li a { color: #000; text-decoration: none; font-weight: 900; line-height: 1.5; } ul:before { content:""; position: absolute; z-index: -1; position-anchor: --li; background: lightblue; height: .2em; inset: auto anchor(right) anchor(bottom) anchor(left); transition: .2s .2s; } ul li { position: relative; } ul li:before { content:""; position: absolute; z-index: -1; inset: 100% -.15em 0; background: lightblue; transition: .2s; } ul li:is(:hover,.active):before { anchor-name: --li; top: 0; transition: .2s .4s; } ul:has(li:hover) li.active:not(:hover):before { anchor-name: none; inset: 100% -.15em 0; transition: .2s; } body { margin: 0; min-height: 100vh; display: grid; place-content: center; background: #f2f2f2; font-family: system-ui, sans-serif; }
ドットのアニメーションが楽しいホバーエフェクト
<nav> <ul> <li><a href="#">Home</a></li> <li class="active"><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul> </nav>
ul { margin: 0; padding: 0; list-style: none; display: flex; gap: 1rem; font-size: 2.2rem; isolation: isolate; } ul li a { color: #000; text-decoration: none; font-weight: 900; line-height: 1.6; } ul:before { content:""; position: absolute; z-index: -1; position-anchor: --li; background: lightblue; height: .4em; border-radius: 5em; inset: auto calc(anchor(center) - .2em) anchor(bottom) calc(anchor(center) - .2em); transition: .3s .2s,.3s .2s cubic-bezier(0,-900,1,-900) bottom; } ul li { position: relative; } ul li:before { content:""; position: absolute; z-index: -1; inset: 100% 50% 0; border-radius: 50%; background: lightblue; transition: .2s; } ul li:is(:hover,.active):before { anchor-name: --li; inset: 0 -.15em; border-radius: 0%; transition: .2s .5s; } ul:has(li:hover) li.active:not(:hover):before { anchor-name: none; inset: 100% 50% 0; border-radius: 50%; transition: .2s; } /* the hacky part of the code (related: https://css-tricks.com/advanced-css-animation-using-cubic-bezier/) */ ul:not(#_) li:nth-child(1):before{bottom: -.1px} ul:not(#_) li:nth-child(2):before{bottom: -.2px} ul:not(#_) li:nth-child(3):before{bottom: -.3px} ul:not(#_) li:nth-child(4):before{bottom: -.4px} ul:not(#_) li:nth-child(5):before{bottom: -.5px} body { margin: 0; min-height: 100vh; display: grid; place-content: center; background: #f2f2f2; font-family: system-ui, sans-serif; }
CSS Anchor Positioning は現在Safari以外で使用できます。 Safariの対応が待ち遠しいですね。
"Anchor Positioning" | Can I use... Support tables for HTML5, CSS3, etc