什麼是CSS偽級以及如何使用它們?
CSS偽類是用於定義元素特殊狀態的關鍵字,可基於用戶交互或文檔位置動態應用樣式;1. :hover在鼠標懸停時觸發,如button:hover改變按鈕顏色;2. :focus在元素獲得焦點時生效,提升表單可訪問性;3. :nth-child()按位置選擇元素,支持odd、even或公式如2n 1;4. :first-child和:last-child分別選中首個和最後一個子元素;5. :not()排除匹配指定條件的元素;6. :visited和:link根據鏈接訪問狀態設置樣式,但:visited受隱私限制;偽類以冒號開頭,可鍊式使用如a:hover:focus,且需遵循LVHA順序以確保正確層疊,它們無需HTML定義,由瀏覽器自動應用,能減少JavaScript依賴並增強交互性與可訪問性。
CSS pseudo-classes are keywords added to selectors that specify a special state of the selected element(s). They allow you to style elements based on user interaction, element position in the document, or other conditions that aren't reflected in the HTML structure itself.

Unlike regular classes, pseudo-classes don't need to be defined in the HTML — they're applied automatically by the browser when certain conditions are met.
Common Use Cases and Examples
Pseudo-classes are especially useful for enhancing user experience through dynamic styling without JavaScript.

:hover – Style on Mouse Over
One of the most widely used pseudo-classes. It applies styles when the user hovers over an element.
button:hover { background-color: blue; color: white; }
This makes buttons change color when the mouse pointer is over them.

:focus – Style When Element is Focused
Useful for accessibility and form interactions. It targets elements that receive focus, like inputs or links.
input:focus { border-color: green; outline: 2px solid yellow; }
This helps users see which input field is currently active.
:nth-child() – Target Elements by Position
Select elements based on their position in a parent container.
li:nth-child(odd) { background-color: #f0f0f0; }
This styles every odd list item with a light gray background. You can also use formulas like 2n 1
for more control.
Other variations:
-
:nth-child(even)
– even positions -
:nth-child(3)
– third child -
:nth-child(3n)
– every third child
:first-child and :last-child
Target the first or last element among siblings.
p:first-child { font-weight: bold; } p:last-child { color: gray; }
:not() – Exclude Elements Matching a Condition
Negation pseudo-class. Applies styles to elements that don't match the given selector.
div:not(.special) { opacity: 0.8; }
This reduces opacity of all div
s except those with the class special
.
:visited and :link – Style Links Based on History
Style anchor tags depending on whether they've been visited:
a:link { color: blue; } a:visited { color: purple; }
Note: For privacy reasons, the styles allowed on :visited
are limited (eg, you can't change display
or position
).
How to Use Pseudo-Classes
The syntax is simple:
selector:pseudo-class { property: value; }
You can also chain pseudo-classes:
a:hover:focus { text-decoration: underline; }
This applies only when the link is both hovered and focused.
Key Points to Remember
- Pseudo-classes start with a colon (
:
). - They're dynamic — applied based on user behavior or document state.
- Some pseudo-classes like
:hover
only work with interactive elements unlesstabindex
is added. - Order matters in some cases. For links, follow the LVHA rule:
:link
,:visited
,:hover
,:active
— to ensure correct cascade.
Final Thoughts
Pseudo-classes are powerful tools for creating responsive, interactive designs with pure CSS. They reduce the need for JavaScript in many common UI patterns and improve accessibility when used thoughtfully.
Basically, they let you answer questions like:
- Is the user hovering this button?
- Is this the first item in a list?
- Has this link been visited?
Once you understand how they work, you'll find yourself using them in almost every project.
以上是什麼是CSS偽級以及如何使用它們?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

要更改CSS列表樣式,首先使用list-style-type改變項目符號或編號樣式,1.使用list-style-type設置ul的項目符號為disc、circle或square,ol的編號為decimal、lower-alpha、upper-alpha、lower-roman或upper-roman,2.用list-style:none完全移除標記,3.使用list-style-image:url('bullet.png')替換為自定義圖像,4.通過list-style-position:in

使用CSS創建點狀邊框只需設置border屬性為dotted即可,例如“border:3pxdotted#000”可為元素添加3像素寬的黑色點狀邊框,通過調整border-width可改變點的大小,較寬的邊框產生更大的點,且可單獨為某一邊設置點狀邊框如“border-top:2pxdottedred”,點狀邊框適用於div、input等塊級元素,常用於焦點狀態或可編輯區域以提升可訪問性,需注意顏色對比度,同時區別於dashed的短線樣式,dotted呈現圓形點狀,該特性在所有主流瀏覽器中均被廣泛

使用純CSS創建響應式自動輪播的推薦語滑塊是可行的,只需結合HTML結構、Flexbox佈局和CSS動畫。 2.首先構建包含多個推薦語項的語義化HTML容器,每個.item包含引用內容和作者信息。 3.通過設置父容器display:flex、width:300%(三張幻燈片)並應用overflow:hidden實現橫向排列。 4.利用@keyframes定義從0%到-100%的translateX變換,配合animation:scroll15slinearinfinite實現無縫自動滾動。 5.添加媒體

CSSgradientsprovidesmoothcolortransitionswithoutimages.1.Lineargradientstransitioncolorsalongastraightlineusingdirectionsliketobottomorangleslike45deg,andsupportmultiplecolorstopsforcomplexeffects.2.Radialgradientsradiatefromacentralpointusingcircleo

要創建CSS的玻璃擬態效果,需使用backdrop-filter實現背景模糊,設置半透明背景如rgba(255,255,255,0.1),添加細微邊框和陰影以增強層次感,並確保元素背後有足夠視覺內容;1.使用backdrop-filter:blur(10px)模糊背景內容;2.採用rgba或hsla定義透明背景控制通透程度;3.添加1pxsolidrgba(255,255,255,0.3)邊框及box-shadow提升立體感;4.確保容器具有豐富背景如圖片或紋理以呈現模糊穿透效果;5.為兼容舊瀏

Usebuilt-incursortypeslikepointer,help,ornot-allowedtoprovideimmediatevisualfeedbackfordifferentinteractiveelements.2.ApplycustomcursorimageswiththecursorpropertyusingaURL,optionallyspecifyingahotspotandalwaysincludingafallbacklikeautoorpointer.3.Fol

Grid-template-areaspropertyallowsdevelopspocrockearteeintuitive,ReadableLayoutsByDefiningNemedGridareas; everystringrepresentsarowresentsarowandeashwordeachwordaColumnCell,withGrid-areanamesonamesonameSonemaneMeAnemesonChildEllementsMatchingThoseNoseNementsMatchingTheSoseIntheTemplate,suchans'headerheaderheaderheaderheaderheaderheaderheaderheader for for for for for for

要添加盒陰影,使用box-shadow屬性;1.基本語法為box-shadow:水平偏移垂直偏移模糊半徑擴展半徑顏色內陰影;2.前三個值必填,其餘可選;3.使用rgba()或hsla()實現透明效果;4.正擴展半徑擴大陰影,負值縮小;5.可通過逗號分隔添加多個陰影;6.應避免過度使用,確保在不同背景上測試可見性;該屬性瀏覽器支持良好,合理運用可提升設計質感。
