国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end CSS Tutorial Relational and Attribute Selectors in CSS3

Relational and Attribute Selectors in CSS3

Feb 18, 2025 am 09:14 AM

Relational and Attribute Selectors in CSS3

以下摘錄自 Alexis Goldstein、Louis Lazaris 和 Estelle Weyl 合著的書籍《HTML5 & CSS3 for the Real World, 2nd Edition》。本書在全球各地的商店有售,您也可以在此處購(gòu)買電子書版本。

Core points

  • CSS3 選擇器允許對(duì)網(wǎng)頁上的元素進(jìn)行精確定位,擴(kuò)展了先前 CSS 版本的功能。 Relational selectors and attribute selectors are key features of CSS3.
  • Relationship selector locates elements based on their relationships in the tag. These include descendant combiners (E F), subcombinator (E > F), adjacent sibling selectors or next sibling selectors (E F), and universal sibling selectors or subsequent sibling selectors (E ~ F).
  • The attribute selector in CSS3 allows matching based on the attributes of the element, and CSS3 extends the attribute selector of CSS2 by allowing pattern matching. These include E[attr], E[attr=val], E[attr|=val], E[attr~=val], E[attr^=val], E[attr$=val], and E[attr* =val]。
  • All modern browsers support CSS3 selectors, including IE9 and later. Using these selectors can greatly improve the efficiency and effectiveness of web design and development.

CSS3 選擇器

CSS 選擇器是 CSS 的核心。 If there is no selector to locate elements on the page, the only way to modify the element's CSS attribute is to use the element's style attribute and declare the style inline, which is both clumsy and difficult to maintain.因此我們使用選擇器。 Initially, CSS allows matching elements by type, class, and/or ID.這需要向我們的標(biāo)記中添加類和 ID 屬性來創(chuàng)建掛鉤,并區(qū)分相同類型的元素。 CSS2.1 添加了偽元素、偽類和組合器。使用 CSS3,我們可以使用各種選擇器來定位頁面上的幾乎任何元素。

在下面的描述中,我們將包含早期 CSS 版本中提供給我們的選擇器。 They are included because while we can use CSS3 selectors, selectors earlier than CSS3 are also part of the CSS selector level 3 specification and are still supported because CSS selector level 3 extends them. Even for selectors that have been around for quite some time, it's worth reviewing here, as there are some little-known hidden gems in the old specification. Please note that all modern browsers, including IE9 and later, support all CSS3 selectors.

關(guān)系選擇器

Relationship selector locates elements based on their relationships in the tag. All of this is supported starting with IE7 and in all other major browsers:

Descendant Combinator (E F)

You should definitely be familiar with this. The descendant selector locates any element F that is descendant of element E (child elements, grandchild elements, great-grandchild elements, etc.). For example, ol li locates li elements that are located in an ordered list. This will include the li element nested in ul in ol, which may not be what you want.

Subcombinator (E > F)

This selector matches any element F as the direct child element of element E - any further nested elements will be ignored. Continuing with the example above, ol > li will only locate the li elements that are directly within ol and will ignore those elements nested within ul.

Neighbor Brother Selector or Next Brother Selector (E F)

This will match any element F that shares the same parent element as E and is directly behind in the tag. For example, li li will locate all li elements in a given container, except for the first li element.

Universal Brother Selector or Subsequent Brother Selector (E ~ F)

This is a bit tricky. It will match any element F that shares the same parent element as any E and is behind it in the tag. Therefore, h1 ~ h2 will match any h2 that lies after h1, as long as they all share the same direct parent element—that is, as long as h2 is not nested in any other element.

Let's look at a simple example:

<header>
  <h1>Main title</h1>
  <h2>This subtitle is matched</h2>
</header>
<article>
  <p>blah, blah, blah …</p>
  <h2>This is not matched by h1 ~ h2, but is by header ~ h2</h2>
  <p>blah, blah, blah …</p>
</article>
The selector strings h1 ~ h2 will match the first h2, because h1 and h2 are both children of the header or direct descendants. The next h2 you will see in the code snippet does not match because its parent element is an article, not a header. However, it will match header ~ h2. Similarly, h2 ~ p only matches the last paragraph, because the first paragraph is before h2 it shares with the parent element article.

Note: Why is there no "parent" selector?

You will notice that so far there are no "father" or "ancestor" selectors, nor "pre-brother" selectors. The performance of the browser having to traverse the DOM tree backwards or recursive to a nested element set before deciding whether to apply the style, preventing the ability to have a native "traverse the DOM tree upwards" selector.

jQuery contains :has() as an ancestor selector. This selector is being considered for CSS selector level 4, but has not been implemented in any browser. If and when it is implemented, we will be able to use E:has(F) to find E with F as descendant, E:has(> F) to find E with F as direct child element, E:has( F) to find E directly before Brother F, and similar.

Browse the style sheets of The HTML5 Herald and you will see that we use these selectors in many places. For example, when determining the overall layout of the site, we want the divs of the three columns to float to the left. To avoid applying this style to any other div nested inside it, we use a sub-selector:

main > div {
  float: left;
  overflow: hidden;
}
As we add new styles to the site in the next few chapters, you will see many of these selector types.

Attribute selector

CSS2 introduces several property selectors. These allow matching based on the element's attributes. CSS3 extends these property selectors to allow some positioning based on pattern matching. CSS selector level 4 has added some more:

E[attr] Matches any element E with the attribute attr regardless of the value of the attribute. We used it in Chapter 4 to style the required input; input:required works in the latest browsers, but input[required] has the same effect and works in IE7 and IE8.

E[attr=val] Matches any element E with the attribute attr and its value is val. Although not new, it is useful when locating form input types; for example, use input[type=checkbox] to locate the checkbox.

E[attr|=val] Matches any element whose attribute attr has a value of val or starts with val- . This is most commonly used in the lang attribute. For example, p[lang|="en"] will match any paragraph defined in English, whether in British or American English, using

or

.

E[attr~=val] Matches any element whose attribute attr contains the full word val (enclosed by spaces). For example, .info[title~=more] will match any element with class info and the title attribute contains the word "more", such as "Click here to learn more".

E[attr^=val] Matches any element whose attribute attr starts with the value val. In other words, val matches the beginning of the property value.

E[attr$=val] Matches any element whose attribute attr ends with . In other words, val matches the end of the property value.

E[attr=val] Matches any element whose attribute attr matches val at any position. It's similar to E[attr~=val], except that val can be part of a word. Using the same example as before, .fakelink[title=info] {} will match any element with class fakelink and the title attribute contains the string info, such as "Click here to learn more".

In these property selectors, the value of val is case sensitive for case-sensitive value in HTML. For example, input[class^="btn"] is case sensitive because class names are case sensitive, but input[type="checkbox"] is case sensitive because type values ??are case-insensitive in HTML.

If the value is alphanumeric, the value is not necessary, but there are some exceptions. Empty strings, strings starting with numbers, two hyphens and other special cases need to be enclosed in quotes. Since there are exceptions, it is a good idea to develop the habit of always including quotes for situations where quotes are required.

In CSS selector level 4, we can achieve case-insensitiveness by including an i before the end bracket, E[attr*=val i].

FAQs about relational selectors and attribute selectors in CSS3

What is the difference between a relation selector and a property selector in CSS3?

The relationship selector in CSS3 is used to select elements based on their relationship with other elements in an HTML document. For example, child elements, descendants, neighboring brothers, and universal brother selectors are all types of relational selectors. On the other hand, the attribute selector is used to select an element based on its attribute or attribute value. For example, you can use the property selector to select all input elements with a type attribute of "text".

How to use a subcombinator in CSS3?

The subcombinator in CSS3 is represented by the ">" symbol. It is used to select direct child elements of a specific element. For example, if you want to select all direct child div elements of the parent element with class "parent", you should write the following CSS:

.parent > div { /* CSS 屬性在此處 */ }

Can I use multiple property selectors in CSS3?

Yes, you can use multiple property selectors in CSS3. This allows you to select elements that meet multiple attribute conditions. For example, if you want to select all input elements with type attribute "text" and name attribute "username", you should write the following CSS:

input[type="text"][name="username"] { /* CSS 屬性在此處 */ }

What is the purpose of the adjacent brother combinator in CSS3?

The adjacent brother combiner in CSS3 is represented by the " " symbol. It is used to select elements that are directly behind another specific element, and the two elements share the same parent element. For example, if you want to select a div element that is directly behind the p element, you should write the following CSS:

p div { /* CSS 屬性在此處 */ }

How to select an element with a specific attribute value in CSS3?

To select an element with a specific attribute value in CSS3, use the attribute selector, attribute name, and value with square brackets. For example, if you want to select all input elements with type attribute "text", you should write the following CSS:

input[type="text"] { /* CSS 屬性在此處 */ }

Can I combine relationship selectors and attribute selectors in CSS3?

Yes, you can combine relationship selectors and attribute selectors in CSS3. This allows you to select elements based on their relationship with other elements and their properties. For example, if you want to select all direct child input elements of a form element with class "form", where the type attribute of the input element is "text", you should write the following CSS:

form.form > input[type="text"] { /* CSS 屬性在此處 */ }

What is the universal brother combinator in CSS3?

The universal sibling combiner in CSS3 is represented by the "~" symbol. It is used to select sibling elements of a specific element, regardless of their order in the HTML document. For example, if you want to select all sibling div elements of the p element, you should write the following CSS:

p ~ div { /* CSS 屬性在此處 */ }

How to select elements in CSS3 that do not have specific attributes?

To select elements that do not have specific attributes in CSS3, use the :not() pseudo-class with attribute selector. For example, if you want to select all input elements whose type attribute is not "submit", you should write the following CSS:

input:not([type="submit"]) { /* CSS 屬性在此處 */ }

Can I use relationship selectors in CSS3 with pseudo-classes?

Yes, you can use relation selectors in CSS3 with pseudo-classes. This allows you to select elements based on their relationship with other elements and their state. For example, if you want to select all direct child a elements of the navigation element that are being hovered, you should write the following CSS:

nav > a:hover { /* CSS 屬性在此處 */ }

How to select an element in CSS3 that contains a specific attribute with a specific value?

To select an element that contains a specific attribute with a specific value in CSS3, use the square bracketed property selector, attribute name and value, and the *= operator. For example, if you want to select all the a elements with href attributes containing "example", you should write the following CSS:

a[href*="example"] { /* CSS 屬性在此處 */ }

The above is the detailed content of Relational and Attribute Selectors in CSS3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How can I include CSS only on some pages? How can I include CSS only on some pages? Jun 11, 2025 am 12:01 AM

There are three ways to selectively include CSS on a specific page: 1. Inline CSS, suitable for pages that are not frequently accessed or require unique styles; 2. Load external CSS files using JavaScript conditions, suitable for situations where flexibility is required; 3. Containment on the server side, suitable for scenarios using server-side languages. This approach can optimize website performance and maintainability, but requires balance of modularity and performance.

Flexbox vs Grid: Understanding the Key Differences in CSS Layout Flexbox vs Grid: Understanding the Key Differences in CSS Layout Jun 10, 2025 am 12:03 AM

Flexboxisidealforone-dimensionallayouts,whileGridsuitstwo-dimensional,complexlayouts.UseFlexboxforaligningitemsinasingleaxisandGridforprecisecontroloverrowsandcolumnsinintricatedesigns.

Creating an Auto-Closing Notification With an HTML Popover Creating an Auto-Closing Notification With an HTML Popover Jun 10, 2025 am 09:45 AM

The HTML popover attribute transforms elements into top-layer elements that can be opened and closed with a button or JavaScript. Popovers can be dismissed a number of ways, but there is no option to auto-close them. Preethi has a technique you can u

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

How to use Lotties in Figma How to use Lotties in Figma Jun 14, 2025 am 10:17 AM

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Jun 13, 2025 am 11:33 AM

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

See all articles