CSS Selector detailed

Source: Internet
Author: User
Tags unique id

    • 1. Element Selector
    • 2. Class Selector
    • 3. ID Selector
    • 4. Attribute Selector
    • 5. Derivation Selector
1. Element Selector

The most common CSS selector is the element selector, which in an HTML document usually refers to an HTML element, such as P,h2,span,a,div or HTML.

The usage is very simple, for example:

html {background-color: black;}p {font-size: 30px; backgroud-color: gray;}h2 {background-color: red;}

The above CSS code adds a black background to the entire document, sets all P element font sizes to 30 pixels and adds a gray background, and adds a red background to all H2 elements in the document.

The basic rule structure of CSS is also shown in the above example: it consists of a selector and a declaration block . Each declaration block contains one or more declarations. The format for each declaration is: 属性名 : 属性值 . As shown in the following:

Each declaration is separated by a semicolon ";" End. if an incorrect property value, or an incorrect property, is used in a declaration, the declaration is ignored. Also, be careful not to forget the semicolon behind each statement.

Let's cite an incorrect example:

p { background-color: red    font-family: 黑体;    wordsize: 20px;    float: left;  }

The above example first declares that a semicolon is missing, and the above declaration block is parsed as:

p {  background-color: red font-family: 黑体;     wordsize: 20px;     float: left;     }

red font-family: 黑体The whole will be parsed into a property value of Background-color, which is certainly not a valid property value, and the declaration will be ignored. In addition, the second declaration uses the incorrect property name Wordsize, which will be ignored, and the result will only correctly handle the third declaration, equivalent to:

p {float: left;}

In addition, we can declare multiple HTML elements at the same time:

h1, h2, h3, h4, h5, h6, p {font-family: 黑体;}

This will set all H1~h6 and P element fonts in the document to "bold".

If we want to porridge all the elements, we can use the wildcard character "*":

* { font-size: 20px;}

All elements will be selected, and although the Font-size property is not valid for some elements, it will be ignored.

2. Class selector (1) Single class selector

Simple element selectors seem to be too coarse, for example, we want to highlight some important content in the document, such as the date of the manuscript. The problem is that we cannot determine which element the deadline for a manuscript will appear in, or it may appear in many different elements. At this point, we can consider using class selector.

To use the class selector we need to first add a class attribute to the file element, such as the up date may appear in the following elements:

<p class="deadline">...</p>

This allows us to use the class selector in the following ways:

p.deadline { color: red;}h2.deadline { color: red;}

dot "." A class selector is formed by adding the class name. The above 2 selectors select all p elements and H2 elements that contain the "Deadline" class. The rest of the elements that contain the attribute are not selected.

If we omit the element name in front of the. deadline, then all elements that contain the class will be selected:

.deadline { color: red;}

Typically, we will combine the above 2 to get a more interesting style:

.deadline { color: red;}span.deadline { font-style: italic;}

The above code first sets all the element fonts that contain deadline to red and adds an extra italic effect to the text in the SPAN element. This way, if you want some text to have an extra italic effect, put them in <span></span> .

(2) Multi-class Selector

In practice, the CALSS attribute of an element may contain more than one word, but rather a string of words, separated by a space between each word.

For example, some elements contain a "warning" class, some elements contain a "important" class, and some elements contain the "warning important" class. The order in which property names appear is not related:

class = "warning important"class = "important warning"

The above 2 are equivalent.

We want the element containing the warning class to have an eye-catching red font, the element containing the important attribute has a bold font display, and the elements that contain the attributes above 2 have a blue background (whether or not you can see the text again), we can use the following CSS code:

.warning { color: red;}.important { font-weight: bold;}.warning.important { background: blue;}

Of course, the third one can also be written as:

.important.warning { background: blue;}

is not related to word order.

As a description, .warning all elements that contain the warning attribute are matched, regardless of how many other attributes the element contains. .importantsimilarly. .important.warningit will match all elements that contain the 2 attributes above, regardless of how many other classes it contains, and regardless of the order in which they appear in the class list, as long as they contain these 2 attributes, they will be chosen!

Similarly, more than one class selector, preceded by the element name, matches the specified element that contains the specified class name, for example:

p.warning.important {}

Will match the P element that contains both the warning and important attributes, and other elements that also contain the above 2 classes will not be selected.

3. ID Selector

The ID selector and class selector are somewhat similar, but the difference is significant.

First an element cannot have more than one class as a class property, and an element can have only one unique ID attribute. The second ID value can only appear once in an HTML document, which means that an ID can uniquely identify an element (not a class of elements, but an element).

Similar to the Class property, you first add the id attribute to the element before using the ID selector, for example:

<p id="top-para">...</p><p id="foot-para">...</p>

Use the ID selector for the ID value followed by the pound sign "#" . Now we use the ID selector to select the above 2 p elements as follows:

#top-para {}#foot-para {}

This allows us to perform the required operations on the above 2 paragraphs. The uniqueness of the ID selector makes it relatively simple to use.

4. Attribute Selector

The property selector is introduced in CSS2 so that we can select elements based on their attributes and property values. The following are respectively explained:

(1) Simple attribute Selector

A simple property selector allows us to make a selection based on whether an element contains a property. Use the following method:

元素名[属性名] 或 *[属性名]

For example, we want to select all the IMG elements with the ALT attribute:

img[alt] { ...}

Select all elements with the title property:

*[title] { ...}

Similar selectors, we can also select based on multiple attribute information, such as the A element with both href and title:

a[href][title] { ...}

Combining the class selector makes our choices more flexible.

(2) specific attribute value Selector

If we want to select elements more precisely based on attribute values, we can specify the value of the property in a simple property selector. The simplest we want to find is an http://www.baidu.com anchor element with the href attribute value:

a[href="http://www.baidu.com"] { font-weight: bold;}

It is important to note that the exact value match here is essentially a string match, so the order of the entries here is related to the class attribute!

p[class="warning important"] { ...}

will not match and will <p class="important warning"></p> not match <p class="warning important mini-type"> , here is a stiff string match.

Also, it is possible to match the values of multiple properties simultaneously:

p[class="warning"][title="para"] { ...}

Will match to class warning (only warning), and the Title property is para p element.

(3) Partial attribute value Selector

Matching elements based on attribute values is undoubtedly more granular than simple attribute matching, but it seems to be a bit more subtle, and the exact match of the strings is too stiff. For example, we want to choose a string of attribute values in the occurrence of a keyword element, we would like to take the class attribute as an example, we want to select all the P element containing the warning class, the property value matching will not be able to do, fortunately there is a way, we can use the following partial value matching selector:

p[class~="warning"] { ...}

The selector adds a tilde, preceded by the equal sign "=", meaning a match that contains the following string. The above code will select all P elements that contain "warning" in the class attribute. To illustrate the problem more clearly, it is equivalent to the following selectors:

p.warning { ...}

Of course ~= It's not just a class attribute, it's just an example.

In other words, our document contains a series of DIV elements that are described by the characters:

<div title="intro 1">...</div><div title="intro 2">...</div><div title="intro 3">...</div>

We can use the following methods to select all the profile div:

div[title~="intro"] { ...}

Unfortunately <div title="animal intro"> , it will also be chosen, which is something that needs our special attention.

There is also a limitation to the partial value selector, which matches a space-delimited word, and fails if we write the above div as follows:

<div title="intro-1">...</div><div title="intro-2">...</div><div title="intro-3">...</div>

For this scenario, we can use substrings to match the property selector . The rules are as follows:

div[title^="intro"] {...}  //title以intro开头的div元素div[title$="intro"] {...}  //title以intro结尾的div元素div[title*="intro"] {...}  //title中包含"intro"子串的div元素

For example:

a[href*="google."] {...}  

Will include all links that contain "Google." The A element.

div[title$="y"] {...}

Will contain all of the following DIV elements:

<div title="cloudy">...</div><div title="snowy">...</div><div title="rainy">...</div>

You can see that the function of the partial Value property selector is very powerful.

5. Derivation Selector

Derived selectors, at first glance the name is unintelligible, it is also called the context selector, it is using the document DOM structure for CSS selection. The DOM structure is not described here, but to illustrate the problem more clearly, we give a DOM tree as a reference:

(1) descendant selector (descendant selector)

For example, if you want to select all the Li child elements of the BODY element, the method is as follows:

body li { ...}

All Li descendants are selected here, that is, all Li under the body of the figure, regardless of the number of algebra between them .

Similarly, if you want to select a span under the H1 element, you can use the following code:

h1 span { ...}

If we want to select Li descendants that have elements of the warning class, you can use the following method:

.warning li { ...}

Of course, if you want to select only Li descendants that have div elements of the warning class, you can write:

div.warning li { ...}

It is not difficult to see from the above example that the rule of the descendant selector is to connect 2 or more selectors with a space . The meaning of the space is: ... Descendants of the . The case for multiple selectors is as follows:

In this way, all of the LI elements under the LI element are selected under all UL, which sounds very awkward, referring to our DOM tree, which selects the last row of LI elements in the document tree.

(2) Sub-element selector (child selector)

Unlike child element selectors and descendant selectors, it can select only the immediate descendants of an element and cannot be selected across generations, using the following:

ul > li { ...}

Two child elements in the middle with a greater than sign > connection. The above code selects the direct Li child elements of all UL elements. To the DOM tree, all the LI elements are selected because all the LI elements in the diagram are sub-elements of the UL.

However, the following code will not select any elements:

h1 > span { ...}

Since span is the "grandson element" of H1, H1 does not have a direct span child element, so the above code will not select any results. Other aspects are similar to the descendant elements, and it is important to note that the child element selector cannot be selected on alternate generations .

(3) Adjacent Brother selector (adjacent sibling selector)

Adjacent sibling selector, so the name of the idea will select an element of the adjacent sibling elements, note that it selects the adjacent sibling elements rather than all the sibling elements, in fact, the selection is immediately following the sibling elements .

Adjacent sibling selectors have good applications in practice, for example, if you want to apply a particular style to a paragraph that is behind a H2 title, or you want to add an extra margin to a table that falls behind a class P segment, and so on.

Its usage is as follows:

li + li { ...}

The above code selects all Li elements that are adjacent to Li, and sounds a bit awkward, referring to the DOM tree, which selects the remaining 4 Li elements in addition to the first LI element, because 2 of the LI elements in the 1th row do not have a more forward sibling element to select it.

Another example:

h1 + p { ...}

Selects all the P-sibling elements immediately following the H1.

h1.warning + p { ...}

Selects the P-sibling element immediately following the H1 element of all useful warning classes.

(4) Combined use of several derivative selectors

In fact, several of the derived selectors described above can be used together to see the following example:

html > body li.warning + li { ...}

The above selector means: In the body child element of the HTML element, all adjacent sibling elements that have the LI element of the warning class.

CSS Selector detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.