Conquer advanced CSS Selector

Source: Internet
Author: User
Tags processing text

CSS is one of the most powerful tools available to web designers. Using it, we can change the interface of a website within several minutes without changing the tab of the page. But while in fact, each of us realizes that it is useful, CSS selectors are far from exploiting their potential, sometimes we tend to use too many useless classes, IDs, Div, and span to make our HTML messy.

The best way to avoid spreading these "plague" in your tags and maintain their simplicity and semantics is to use more complex CSS selectors, they can be positioned on specified elements without additional classes or IDs. In addition, they can make our code and style more flexible.

CSS priority

It is important to understand how CSS priorities work before you study the advanced CSS selector field in depth, in this way, we will know how to properly use our selector and avoid wasting a lot of time debugging problems that can be easily solved as long as we notice the priority.

When writing CSS, we must note that some selectors are higher than other selectors in cascade, the selector we write at the end will not necessarily overwrite the style we write in the same element above.

So how do you calculate the priority of a specified selector? It would be quite simple if you think that the priority is represented by four numbers separated by commas, such as: 1, 1, 1, 1 or 0, 2, 0, 1

The first number (a) is usually 0, unless the style attribute is used on the label;

The second number (B) is the total number of IDs on the selector;

The third digit (c) is the sum of other attribute selectors and pseudo classes used on the selector. This includes Class (. Example) and attribute selector (for example, Li [ID = Red]);

The fourth digit (d) calculates elements (such as table, P, Div, etc.) and pseudo elements (such as: first-line );

The general selector (*) has a priority of 0;

If the two selectors have the same priority, the one next to the style sheet takes effect.

Let's look at several examples to make it easier to understand:

# Sidebar H2-0, 1, 0, 1

H2.title-0, 0, 1, 1

H2 + P-0, 0, 0, 2

# Sidebar P: first-line-0, 1, 0, 2

In the following example, the first one will take effect because it is higher than the second one:

# Sidebar P # first {color: red;}-0, 2, 0, 1

# Sidebar P: first-line {color: Blue;}-0, 1, 0, 2

At least it is important to understand how priorities work. However, some tools such as firebug, when we review specific elements, listing all CSS selectors Based on the selector's priority helps us to know which selector is valid on the specified element.

 

You can easily see that the selector acts on an element.

 

1. Attribute Selector

Attribute selector allows you to locate an element based on attributes. You can only specify an attribute of this element, so that all elements that use this attribute, regardless of its value, will be located, it can also be more explicit and positioned to use elements with specific values on these attributes-this is where the attribute selector shows their power.

There are six attribute selectors of different types:

[ATT = value]

This attribute has the specified exact value.

[ATT ~ = Value]

The value of this attribute must be a series of multiple values separated by spaces (for example, class = "title featured home "), and one of these values must be the specified value "value ".

[ATT | = value]

The attribute value is "value" or starts with "value" and immediately follows the "-" character, that is, "value -". (For example, lang = "ZH-CN ")

[ATT ^ = value]

The value of this attribute starts with the specified value.

[ATT $ = value]

The value of this attribute contains the specified value (regardless of its location ).

[ATT * = value]

The value of this attribute ends with the specified value.

For example, if you want to change the background color of some elements in logs on your blog, you can use an attribute selector that specifies the attribute values of each class starting with "post:

Div [class | = "Post"] {

Background-color: #333;

}

This statement matches all DIV elements whose class attributes contain the "post" and contain the "-" character. (Note: Some Original English texts do not correspond to each other. I have corrected them-translator, shenfei)

Another useful use of the attribute selector is to locate different types of input elements. For example, if you want your text input box to use a specific width, you can use the following attribute selector:

Input [type = "text"] {

Width: 200px;

}

This will match all input elements whose type property value is equal to "text.

Now we may add different icons for different file types of links on the website, in this way, visitors of your website will know that they will get an image, a PDF file, or a Word document. This can be achieved using the attribute selector:

A [href * 00000000.jpg "] {

Background: url().gif) No-repeat left 50%;

Padding: 2px 0 2px 20px;

}

A [href * handle invalid parameters "] {

Background: url().gif) No-repeat left 50%;

Padding: 2px 0 2px 20px;

}

A [href * zookeeper .doc "] {

Background: url(word.gif) No-repeat left 50%;

Padding: 2px 0 2px 20px;

}

In this example, we use an attribute selector to locate all links (the href of avel are separated by .jpg, .jpg, .doc or. Doc end. For details, refer to the previous article "using CSS selector to create a personalized link style".

Browser support

All mainstream browsers except Internet Explorer 6 support attribute selectors. This means that if you use the attribute selector on your website, you should ensure that IE6 users will still be able to get a available website. For example, in our third example, adding icons to links can bring another level of availability to your website. However, if these links do not show any icons, the website is still available.

2. Sub-Selector

The sub-selector is represented by the symbol. It allows you to locate the first child element of an element.

For example, if you want to match all the H2 elements of the child element of the DIV column of your website, instead of all the H2 elements in the DIV element, it is not the sun element of the div (or a lower level). You can use the following selector:

Div # sidebar> H2 {

Font-size: 20px;

}

You can also use child and descendant elements at the same time. For example, if you want to locate the BLOCKQUOTE element only in the Child Div element of the Body element (for example, you want to match the blockquotes in the main Div, rather than the other parts:

Body> div> Div BLOCKQUOTE {

Margin-left: 30px;

}

Browser support

Like the attribute selector, the sub-selector is not supported by ie6. If the effect you want to achieve in this way is closely related to the availability or overall design of the website, you can consider using a class or a style only for IE6, however, this is against the purpose of using the sub-selector.

3. Brothers

There are two types of brothers: near brothers and normal brothers.

Near brothers

This selector uses the plus sign "+" to link the first and second selectors. The element in the selector has the same parent, and the second one must closely follow the first one.

Near sibling combinations can be very useful, for example, when processing text. For example, we want to add a top margin "margin-top" to the H2 title after the section (of course, you may not need to add H2 after the H1 tag, or it may be the first element of the page ):

P + H2 {

Margin-top: 10px;

}

You can even be more specific. You want to locate the H2 following a specific Div:

Div. Post P + H2 {

Margin-top: 10px;

}

Or you can make it more complicated: the first line of the first paragraph of the page is displayed with lowercase letters.

. Post H1 + P: first-line {

Font-variant: Small-caps;

}

This may be because the first section of most logs/articles will be closely followed by the H1 tag. You can use the H1 tag in your selector.

Common brothers

The working principle of a common sibling combination is similar to that of a neighboring sibling combination. The difference is that the second option does not need to be followed by the first one.

If you need to locate all the P tags in a specific Div that follow the H1 tag (You may want the text before the title of the log that these p Tags match ), you can use this selector:

. Post H1 ~ P {

Font-size: 13px;

}

Note: The two selectors are too similar. If you do not understand them well, try the following example:

CSS:

P + H2 {color: red;

}

P ~ H2 {font-weight: 700;

}

HTML:

P ke, content. /P

H2 Title 1/H2

H2 Title 2/H2

Let's take a look at the second H2 color? A near sibling combination can only match the first sibling behind the first selector. A normal sibling combination can match all. Note: This part of the original English text does not exist. It is added by myself during the translation of shenfei.

Browser support

Internet Explorer 6 still cannot understand the sibling selector. However, in another case, if only a small part of your users are Internet Explorer 6 users, in addition, the website structure will not be damaged or seriously affected. This achieves many cool effects without adding useless classes or IDs to your HTML code.

4. Pseudo-classes

Dynamic pseudo class

Dynamic pseudo-classes are called because they do not exist in HTML. They are only displayed when users interact with websites.

There are two types of dynamic pseudo classes: links and user behavior. Links are: link and: visited, and user behaviors include: hover,: active, and: focus.

In the CSS selector mentioned in this Article, these should be the most commonly used.

: The Link pseudo-class is used when the link is not accessed by the user, and the visited pseudo class is used for the link accessed by the user, that is, they are opposite.

: The hover pseudo class is used when users move their mouse over the element, but have not yet triggered or clicked it. : The active pseudo class is used when the user clicks an element. Finally, the focus pseudo-class is used when an element becomes the focus-most commonly used for form elements.

You can use a variety of user behavior dynamic pseudo-classes in your style sheet, so that you can, for example, when the user's mouse is only slide or hovering, define different background colors for an input box:

Input: Focus {

Background: # d2d2d2;

Border: 1px solid # 5e5e5e;

}

Input: Focus: hover {

Background: # c7c7c7;

}

Browser compatibility

Dynamic pseudo-classes are supported by all modern browsers, or even IE6. However, for IE browsers, IE6 only allows: hover pseudo-classes to be applied to link elements (a tag) and only accept by IE8: active.

: First-child

: The first-Child pseudo-class allows you to locate the first child element of an element. For example, if you want to add a margin-top to the first Li in your list, you can write as follows:

Ul> Li: First-child {

Margin-top: 10px;

}

Let's take a look at another example: for example, if you want the H2 tag in the sidebar of your blog to have a top margin to distinguish the title from the content above them, but the first H2 is not required, you can use the following code:

# Sidebar> H2 {

Margin-top: 10px;

}

# Sidebar> H2: First-child {

Margin-top: 0;

}

Browser compatibility

IE6 does not support the first-Child pseudo class. Depending on the design of pseudo-class applications, it may not be a major concern. For example, if you use the: First-Child selector to remove the spacing between the header and the bottom of a title or paragraph, your layout will not break down in IE6, but it will only look a little different. However, if you use the: First-Child selector to remove the left or right margin from a floating element, your design will be messy.

Pseudo-language

Language pseudo-class: Lang (), allowing you to match an element based on its language.

For example, if you want a specific link of your website to have different background colors based on the language of the page:

: Lang (en)> A # flag {

Background-image: url(english.gif );

}

: Lang (FR)> A # flag {

Background-image: url(french.gif );

}

This selector will match the relevant link-if the page language is equal to "en" or "FR ", or start with "EN" or "FR" with a hyphen.

Browser compatibility

Unfortunately, only IE8 in IE supports this selector. Other major browsers support this pseudo-class selector.

5. CSS 3 pseudo class

: Target

When you use an anchor (fragment identifier), such as http://www.smashingmagazine.com/2009/08/02/bauhaus-ninety-years-of-Inspiration/# comments, this "# comments" is a fragment identifier, you can use the: Target pseudo class to control the target style.

For example, you have a very long page that uses a lot of text and H2 titles, and then you have an index on these headers. If you click a link in the index, the corresponding title is highlighted in some way and then rolled to the corresponding position, which is useful to readers. Very simple.

H2: Target {

Background: # f2ebd6;

}

Browser compatibility

This time, ie does not support the target pseudo class. Another small problem is that opera does not support this selector when using the forward and backward buttons. However, other mainstream browsers support this selector.

Pseudo-type of UI element status

Some HTML elements include the Enable or disabled status (for example, text input box) and checked or unchecked status (single-choice buttons and check boxes ). You can use the enabled, disabled, or checked pseudo classes to locate these statuses respectively.

Then you will think that if any disabled text box should use a light gray background and dotted border:

Input: Disabled {

Border: 1px dotted# 999;

Background: # f2f2f2;

}

You may also want to have a left margin for all selected check boxes (this makes it easy to recognize among the many check boxes ):

Input [type = "checkbox"]: checked {

Margin-left: 15px;

}

Browser compatibility

All mainstream browsers, except the IE browsers that we often do not want, support the pseudo-class UI element status. If you only consider adding additional-level details and enhancing the availability of your website, this can still be used.

6. CSS 3 structure pseudo class

: Nth-child

: The Nth-child () pseudo class allows you to locate one or more specific child elements of a parent element.

You can define its value as an integer to locate a single sub-element:

Ul Li: Nth-child (3 ){

Color: red;

}

This will change the text of the third li element of the UL element to red. Note that if there is another type of element (not li) in UL, it will also be counted as its child element.

You can use expressions to locate child elements. For example, the following expression matches each third element from the fourth element.

Ul Li: Nth-child (3N + 4 ){

Color: yellow;

}

In the above example, the first yellow Li element will be the fourth. If you want to start matching from the first one, you can use a simple expression:

Ul Li: Nth-child (3N ){

Color: yellow;

}

In this case, the first yellow Li element will be the third child element, and then the third child element after it. Now imagine if you only want to match the first four child elements in the list:

Ul Li: Nth-child (-N + 4 ){

Color: green;

}

: The value of Nth-child can also be defined as "even" or "odd", and "2n" (even number) or "2n + 1" (odd number) the effect is the same.

: Nth-last-child

The: Nth-last-Child pseudo class basically functions the same as the: Nth-Child pseudo class, but it starts from the last element.

Let's take a look at the example above:

Ul Li: Nth-child (-N + 4 ){

Color: green;

}

Instead of matching the first four Li elements, the selector matches the last four elements.

You can also use "even" or "odd" only. Unlike Nth-child, this is calculated from the final element:

Ul Li: Nth-last-child (ODD ){

Color: Gray;

}

: Nth-of-type

The: Nth-of-type pseudo class is similar to: Nth-child. The difference is that it only calculates the element specified in the selector.

This is useful when positioning elements contain a large number of different elements. For example, we want to control every paragraph in a text block, but we want to ignore other elements and reference blocks:

P: Nth-of-type (even ){

Color: blue;

}

You can also use some values, just as they are used in: Nth-child.

: Nth-last-of-type

Can you guess it ?! : Nth-last-of-type can be used as mentioned earlier: Nth-last-child. However, this time, it matches the element type you specified in the selector:

Ul Li: Nth-last-of-type (-N + 4 ){

Color: green;

}

We can be smarter, and combine a variety of such pseudo classes in a large block-level selector. For example, we want to make all the pictures in the article float left, except the first and last ones (we can assume they are full width without floating ):

. Post IMG: Nth-of-type (n + 2): Nth-last-of-type (n + 2 ){

Float: left;

}

So in the first part of this selector, we start from the second image to locate each image. In the second part, we locate all the images except the last one. Because these two selectors are not mutually exclusive, we can use them at the same time, so that we can immediately exclude the first and last elements!

: Last-child

: The last-Child pseudo class is similar to the first-Child pseudo class, but the last child element of the parent element is located.

Let's assume that you do not want the last section of your log Div to have a bottom margin:

. Post> P: Last-child {

Margin-bottom: 0;

}

This selector locates the last direct child section of the element whose class is "Post.

: First-of-type and: Last-of-type

: The first-of-type pseudo-class is used to locate the first child element of the same type under a parent element.

For example, you can locate the first child paragraph (p) of a specific Div and make the first row of uppercase letters:

. Post> P: first-of-type: first-line {

Font-variant: Small-caps;

}

In this selector, you can determine whether you are only locating the direct sub-level P element of the element whose class is "Post" and still matching the first sub-level P element.

The: Last-of-type pseudo-class is similar to this, but matches the last child element.

Nly-child

The nly-Child pseudo class indicates that an element is the only child element of its parent element.

For example, you have some boxes ("news") that contain some text paragraphs. When you have more than one paragraph, you want to make the text smaller than when there is only one paragraph:

Div. News> P {

Font-size: 1.2em;

}

Div. News> P: Only-Child {

Font-size: 1.5em;

}

In the first selector, we define the font size of all the child P elements of the "news" Div. In the second part, we overwrite the previous font size. If the P element is the only sub-element of the "news" Div, Its font size will be larger.

Nly-of-type

The nly-of-type pseudo-class indicates that an element is the only child element of the same type of its parent element.

What is this useful? Assume that you have some logs. Each article has a class "Post" Div. Some of them have more than one image, but some may only have one image. If you want the image in the latter to be horizontally centered, and other logs with more than one image, it will float left. This requirement can be easily implemented using this selector:

. Post> IMG {

Float: left;

}

. Post> IMG: only-of-type {

Float: none;

Margin: auto;

}

: Empty

: Empty pseudo class indicates that there is no content in an element.

This selector can be used for many purposes. For example, you have several boxes in your "sidebar", but do not want the empty box to be displayed:

# Sidebar. Box: Empty {

Display: none;

}

Note: even if there is only one space in the "box" Div, it will not be treated as an empty tag by CSS, so that it cannot match the selector.

Browser support

Internet Explorer (until version 8.0) does not support structure pseudo classes. Firefox, Safari, and opera indicate these selectors in their latest browsers. This means that using these selectors is useful for website availability and accessibility, or if most of the website's users use IE and you don't want to ignore them in some details, it is better to keep using general class and simple selector to cater to these selector. Otherwise you will be crazy!

7. Negative Selector

Negative selector: Not (), which allows you to locate the element that does not match the selector.

For example, if you need to define the input element in a form element, but do not want to include the input of the submit type, it is often useful-you want them to have different styles to look like buttons:

Input: Not ([type = "Submit"]) {

Width: 200px;

Padding: 3px;

Border: 1px solid #000000;

}

In another example, you want all paragraphs (p) in the DIV of your log to have a relatively large font, except for paragraphs that represent time and date:

. Post P: Not (. Date ){

Font-size: 13px;

}

You can imagine the potential that this selector can bring to you. Can you strip (remove) a large number of useless selectors from your CSS files that are also widely supported by it?

Browser support

Internet Explorer is often disappointing here: it is not supported at all, even in IE8. This probably means that these selectors will still have to wait until some developers no longer worry about adding them to their style sheets.

8. pseudo elements

Pseudo elements allow you to operate on elements that are not actually present in HTML, such as the first line or first letter of a text block.

Pseudo elements already exist in CSS 2.1, but the CSS 3 statement indicates that they should use double colons ":" to distinguish them from pseudo classes. In css 2.1, they also use a single colon. The browser will be able to accept two formats, unless these pseudo elements only exist in css3.

: First-line

: The first-line pseudo element will match the first row of level elements such as block, inline-block, table-caption, and table-cell.

This is quite useful for adding some subtle typographical details to your text block. For example, you can change the first line of text in an article to lowercase letters:

H1 + P: first-line {

Font-variant: Small-caps;

}

If you carefully read the previous content, you will understand the syntax above, which means that you closely follow the H1 tag (+) the first line of text is displayed as lowercase letters.

You can also specify the first line of the DIV, instead of the actual section label (P ):

Div. Post P: first-line {font-variant: Small-caps ;}

Or further, locate the first line of the first paragraph of a very low Div:

Div. Post> P: First-child: first-line {

Font-variant: Small-caps;

}

Here, the "" symbol indicates that you specify the direct sub-level element of the post Div, so that if the paragraph is included in the second-level Div, it will not match this selector.

: First-letter

: The first-letter pseudo element will match the first letter of a text block, unless there are some other elements in the same line, such as slices.

Like the: first-line pseudo-class,: First-letter is usually used to add typographical details to text elements, such as sinking letters or initials.

Here is an example of how to use the: First-letter pseudo element to create the first word sink:

P {

Font-size: 12px;

}

P: First-letter {

Font-size: 24px;

Float: left;

}

Note that if you use the: first-line and: First-letter,: First-letter attributes at the same time in some elements, the attributes will overwrite from :: some attributes inherited from first-line.

If you do not know W3C rules, this element sometimes produces unexpected results: it is actually the selector that uses the longest rule! So if you plan to use it, you 'd better read it carefully (the same is true for other selectors ).

: Before and: After

The: before and: After pseudo elements are used to insert content before or after an element. They are pure CSS.

These elements inherit most of the attributes of the elements they will attach.

Suppose you want to add the text "graphic number X:" Before the description of the icon in your page :". You do not need to write the text "graphic number", or manually add a number:

. Post {

Counter-Reset: image;

}

P. Description: Before {

Content: "figure number" counter (image) ":";

Counter-increment: image;

}

So what will happen?

First, we will tell HTML to create an "image" counter. For example, you can add this attribute to the body of the page. We can also give this counter any name, as long as you want, as long as we often use the same name to reference it: Try it yourself!

We want to add this part before each section of the class "Description": "figure number"-note that only the content we write in the quotation marks will be created on the page, so we also need to add a space!

Then we have counter (image): This will use the attributes we previously defined in the. Post selector. It starts from Number 1 by default.

The next attribute indicates that the counter knows that for each P. description, it needs to increase the image counter by 1 (counter-increment: image ).

It is not as complex as it looks, and it is often useful.

: Before and: After pseudo elements often only use the content attribute to add certain phrases or typographical elements, but here we show that we can use them in a more powerful way that combines the Counter-reset and counter-increment attributes.

It is interesting that: first-line and: First-letter pseudo elements can match the content generated by the: Before pseudo element if it exists.

Browser support

If a single colon is used (for example, first-letter, instead of: First-letter), these pseudo elements are supported by IE8 (but not by IE7 or 6 ). However, other mainstream browsers support these selectors.

Conclusion

The boring story is finally over. Now you can understand the essentials of this article and try it by yourself: by creating an experimental page and testing all these selectors, if you have any questions, return here and make sure that the W3C rules are always followed, but do not just sit there and think that these selectors are not fully supported and you will ignore them.

If you dare to take risks, or you are not afraid to give up the useless and non-semantic class and ID all over the world, why don't you try one or two of these powerful CSS selectors to your next project? We promise you will not go back!

Related Article

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.