search
HomeWeb Front-endCSS TutorialCSS Pseudo-classes: :not() and :target

This article explores the versatile CSS pseudo-classes :not() and :target, showcasing their power in creating sophisticated and targeted styles. We'll delve into their functionalities and demonstrate practical applications, including building JavaScript-free tabs.

CSS Pseudo-classes: :not() and :target

Key Concepts:

  • The :not() pseudo-class acts as a filter, selecting all elements except those matching a given selector. This allows for precise exclusion of elements from styling rules.
  • The :target pseudo-class highlights the document section corresponding to a specific URL fragment (the part after the # symbol). This enables creating interactive elements without JavaScript.

JavaScript-less Tabs with :target:

By cleverly manipulating URL fragments and the :target pseudo-class, we can build functional tabbed interfaces without relying on JavaScript. Clicking a tab updates the URL fragment, triggering the :target style on the corresponding tab content, making it the visible layer.

Excluding Elements with :not():

:not()'s power lies in its ability to exclude elements from style rules. However, its current limitation of accepting only a single argument necessitates chaining for multiple exclusions. For instance, input:not([type=radio]):not([type=checkbox]):not([type=range]) selects all input elements except radio buttons, checkboxes, and range inputs. Future CSS specifications promise improved functionality, allowing comma-separated arguments within :not().

CSS Pseudo-classes: :not() and :target

Excerpt from "CSS Master" by Tiffany B. Brown. Available in bookstores and as an ebook.

This section explores advanced pseudo-classes, including child-indexed and typed child-indexed pseudo-classes (selecting elements by position in the document tree) and input pseudo-classes (targeting form fields based on their values and states).

Highlighting Page Fragments:

Fragment identifiers (e.g., #top, #footnote1) are used for in-page navigation. The :target pseudo-class lets us style the section matching the current fragment identifier without JavaScript. For example:

.comment:target {
  background: #ffeb3b;
  border-color: #ffc107;
}

This styles comments with a yellow background when their ID matches the URL fragment.

CSS Pseudo-classes: :not() and :target

CSS Pseudo-classes: :not() and :target

Creating CSS-only Tabs:

The :target pseudo-class is key to creating JavaScript-free tabs. By setting z-index values based on the :target state, we ensure that only the selected tab is visible.

.comment:target {
  background: #ffeb3b;
  border-color: #ffc107;
}
<div class="tabbed-widget">
  <div class="tab-wrap">
    <a href="https://www.php.cn/link/7426f79c9a7f5af0a6cc457b2a7fb195">Tab 1</a>
    <a href="https://www.php.cn/link/60430f4a984aa0a534e027339a7580a7">Tab 2</a>
    <a href="https://www.php.cn/link/9d4f684ba088d28ad1c2ae7d0aee496a">Tab 3</a>
  </div>
  <ul class="tab-body">
    <li id="tab1"><p>This is tab 1.</p></li>
    <li id="tab2"><p>This is tab 2.</p></li>
    <li id="tab3"><p>This is tab 3.</p></li>
  </ul>
</div>

CSS Pseudo-classes: :not() and :target

Accessibility Tip: For better accessibility, consider using JavaScript to manage aria-hidden attributes.

:not() in Action:

The :not() pseudo-class is demonstrated by styling form labels, excluding those with the label-radio class.

[id^=tab] { position: absolute; }
[id^=tab]:first-child { z-index: 1; }
[id^=tab]:target { z-index: 2; }

CSS Pseudo-classes: :not() and :target

Chaining :not() is crucial when excluding multiple element types, as shown below:

label:not(.label-radio) {
  font-weight: bold;
  display: block;
}

This efficiently targets all input types except radio, checkbox, and range.

FAQs on :not() Selector:

This section provides answers to common questions regarding the :not() selector, covering its functionality, browser support, and usage with various CSS selectors. The answers are similar to those in the original text, but rephrased for clarity and conciseness.

The above is the detailed content of CSS Pseudo-classes: :not() and :target. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),