以下摘录自 Alexis Goldstein、Louis Lazaris 和 Estelle Weyl 合著的书籍《HTML5 & CSS3 for the Real World, 2nd Edition》。本书在全球各地的商店有售,您也可以在此处购买电子书版本。
Core points
- CSS3 选择器允许对网页上的元素进行精确定位,扩展了先前 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.这需要向我们的标记中添加类和 ID 属性来创建挂钩,并区分相同类型的元素。 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.
关系选择器
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 id="Main-title">Main title</h1> <h2 id="This-subtitle-is-matched">This subtitle is matched</h2> </header> <article> <p>blah, blah, blah …</p> <h2 id="This-is-not-matched-by-h-h-but-is-by-header-h">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!

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
