之前已經講過 background-image 也說過偽元素了,今天要把兩個結合並搭配偽類實作囉~ Let's go
今天會使用到的偽類是 hover,至於其他偽類還有非常多種,大家可到 tailwind 官網查詢。
先帶大家做一個假設性問題,如果今天我們想要實作 banner 有著 hover 效果,而 hover 效果為圖片放大,如圖:
但實際上剛開始做出來的效果卻是:
以上為筆者親身經歷,之後將背景圖片加入到偽元素整個世界就豁然開朗了
在這邊跟大家分享一下實作過程:
<div
class="before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
></div>
2. 為了讓圖片放大,使用 transform: scale(1.5);
<div
class="before:scale-150 before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
></div>
<div
class="before:scale-150 before:transition-transform before:duration-1000 before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
></div>
<div
class="overflow-hidden before:scale-150 before:transition-transform before:duration-1000 before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
></div>
<div
class="overflow-hidden before:scale-150 before:transition-transform before:duration-1000 before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
>
<h2
class="absolute text-4xl text-white -translate-x-1/2 -translate-y-1/2 top-1/2
left-1/2"
>
Lorem ipsum dolor sit amet.
</h2>
</div>
<div
class="overflow-hidden hover:before:scale-150 before:transition-transform before:duration-1000 before:block before:w-full before:h-[1000px] before:bg-center before:bg-cover before:bg-RS-660"
>
<h2
class="absolute text-4xl text-white -translate-x-1/2 -translate-y-1/2 top-1/2
left-1/2"
>
Lorem ipsum dolor sit amet.
</h2>
</div>
這樣我們的成品就完成了~
這邊要注意的點是,hover 需要加在偽元素 before 之前,且偽類 hover 與偽元素 before 都僅需要一個冒號,下一個章節要來帶大家了解 group-hover,筆者認為這個非常實用,剛開始使用 tailwind 時並沒有發現,導致每次做類似效果都要寫 css,覺得很不 tailwind,大家敬請期待吧!