search
HomeWeb Front-endFront-end Q&AHow to use selector to exclude elements in css

CSS is one of the important skills in front-end development. In addition to the basic selection of elements and modification of styles, selection and exclusion is also a very important knowledge point in CSS. This article will explain selection exclusions in CSS and provide practical cases for reference.

Introduction to selectors

Before learning to select and exclude, let’s first understand the basics of CSS selectors.

CSS selector is used to select HTML elements. In CSS, there are many kinds of selectors, such as basic selectors, hierarchical selectors, pseudo-class selectors, etc. These selectors have different uses and syntax.

The following are several types of basic selectors:

  • Tag selector: Select by the tag name of the HTML element, for example: p{color:red}
  • Class selector: Select through the class attribute of the HTML element, for example: .myclass{color:blue}
  • ID selector: Select through the class attribute of the HTML element ID attribute to select, for example: #myid{color:green}
  • Wildcard selector: select all HTML elements, for example: *{color:pink}
  • Attribute selector: Select through the attribute value of the HTML element, for example: [href="http://www.example.com"]{color:purple}

Through the combination of the above basic selectors, we can accurately select HTML elements and modify their styles through CSS.

Select to exclude

Sometimes we not only need to select elements, but also need to exclude some elements. At this time, selecting to exclude is very useful.

There are several ways to exclude selection in CSS:

  • :not pseudo-class
  • :first-child pseudo-class
  • :last -child pseudo-class
  • :only-child pseudo-class

Let’s introduce them one by one.

:not pseudo-class

:not pseudo-class is used to exclude certain elements. Through simple syntax, we can exclude specified elements in the selector.

For example, we want to select all p elements, but exclude elements with class="no" in the p elements, You can use the following syntax:

p:not(.no){color:blue}

This way you can accurately select all p elements, but exclude elements with class="no" and replace them The text font color is changed to blue.

:first-child pseudo-class

:first-child pseudo-class indicates selecting the first child element, and can also be used to exclude certain elements.

For example, we want to select the first child element a of all li elements, but exclude elements with class="no" Elements, you can use the following syntax:

li > a:first-child:not(.no){color:blue}

This way you can accurately select the first child element a of all li elements, but exclude the elements with class="no" elements, change their text font color to blue.

:last-child pseudo-class

:last-child pseudo-class indicates selecting the last child element, and can also be used to exclude certain elements.

For example, we want to select the last child element li of all ul elements, but exclude those with class="no" element, you can use the following syntax:

ul > li:last-child:not(.no){color:blue}

This way you can accurately select the last child element li of all ul elements, but exclude elements with For elements with class="no", change their text font color to blue.

:only-child pseudo-class

:only-child pseudo-class indicates selecting the only child element, and can also be used to exclude certain elements.

For example, we want to select all div elements, but only the unique child element p, and exclude elements with class="no" elements, you can use the following syntax:

div > p:only-child:not(.no){color:blue}

This way you can accurately select the only child element p of all div elements, but exclude For elements with class="no", change their text font color to blue.

Actual Case

The following provides an actual case to show how to use selection exclusion.

Case description: There is a dynamically generated navigation bar menu, some of which have drop-down menus. Now it is necessary to change the font color of all menus to red, but exclude menus with drop-down menus and their drop-down menus. font color.

HTML code:



CSS code:

.menu li > a:not(.submenu > li > a){
  color: red;
}

Explanation: Through the :not() pseudo-class, we can use The li element of submenu and its child elements submenu > li are excluded, and only all li elements and child elements a are selected. And change its font color to red.

The above is the basic knowledge and practical application of selection exclusion. In actual development, selection exclusion is a very practical technique that can help us select HTML elements and modify their styles more efficiently.

The above is the detailed content of How to use selector to exclude elements in css. 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
useState() vs. useReducer(): Choosing the Right Hook for Your State NeedsuseState() vs. useReducer(): Choosing the Right Hook for Your State NeedsApr 24, 2025 pm 05:13 PM

ChooseuseState()forsimple,independentstatevariables;useuseReducer()forcomplexstatelogicorwhenstatedependsonpreviousstate.1)useState()isidealforsimpleupdatesliketogglingabooleanorupdatingacounter.2)useReducer()isbetterformanagingmultiplesub-valuesorac

Managing State with useState(): A Practical TutorialManaging State with useState(): A Practical TutorialApr 24, 2025 pm 05:05 PM

useState is superior to class components and other state management solutions because it simplifies state management, makes the code clearer, more readable, and is consistent with React's declarative nature. 1) useState allows the state variable to be declared directly in the function component, 2) it remembers the state during re-rendering through the hook mechanism, 3) use useState to utilize React optimizations such as memorization to improve performance, 4) But it should be noted that it can only be called on the top level of the component or in custom hooks, avoiding use in loops, conditions or nested functions.

When to Use useState() and When to Consider Alternative State Management SolutionsWhen to Use useState() and When to Consider Alternative State Management SolutionsApr 24, 2025 pm 04:49 PM

UseuseState()forlocalcomponentstatemanagement;consideralternativesforglobalstate,complexlogic,orperformanceissues.1)useState()isidealforsimple,localstate.2)UseglobalstatesolutionslikeReduxorContextforsharedstate.3)OptforReduxToolkitorMobXforcomplexst

React's Reusable Components: Enhancing Code Maintainability and EfficiencyReact's Reusable Components: Enhancing Code Maintainability and EfficiencyApr 24, 2025 pm 04:45 PM

ReusablecomponentsinReactenhancecodemaintainabilityandefficiencybyallowingdeveloperstousethesamecomponentacrossdifferentpartsofanapplicationorprojects.1)Theyreduceredundancyandsimplifyupdates.2)Theyensureconsistencyinuserexperience.3)Theyrequireoptim

Virtual DOM in React: Boosting Performance Through Efficient UpdatesVirtual DOM in React: Boosting Performance Through Efficient UpdatesApr 24, 2025 pm 04:41 PM

TheVirtualDOMisalightweightin-memorycopyoftherealDOMusedbyReacttooptimizeUIupdates.ItboostsperformancebyminimizingdirectDOMmanipulationthroughaprocessofupdatingtheVirtualDOMfirst,thenapplyingonlynecessarychangestotheactualDOM.

HTML and React's Integration: A Practical GuideHTML and React's Integration: A Practical GuideApr 21, 2025 am 12:16 AM

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)