30 CSS selectors to be remembered

Source: Internet
Author: User
Document directory
  • 1 .*
  • 2. # X
  • 3. X
  • 4. X Y
  • 5.x
  • 6. X: visited and X: link
  • 7. X + Y
  • 8. X> Y
  • 9. X ~ Y
  • 10. X [title]
  • 11. X [href = "foo"]
  • 12. X [href * = "akasuna"]
  • 13. X [href ^ = "http"]
  • 14. X [href $ = ". jpg"]
  • 15. X [data-* = "foo"]
  • 16. X [foo ~ = "Bar"]
  • 17. X: checked
  • 18. X: after
  • 19. X: hover
  • 20. X: not (selector)
  • 21. X: pseudo element
  • 22. X: nth-child (n)
  • 23. X: nth-last-child (n)
  • 24. X: nth-of-type (n)
  • 25. X: nth-last-of-type (n)
  • 26. X: first-child
  • 27. X: last-child
  • 28. X: only-child
  • 29. X: only-of-type
  • 30. X: first-of-type
  • Conclusion

Refer to: http://www.akasuna.com/2011/04/06/the-30-css-selectors-you-must-memorize/

 

Maybe you have learned the css id selector, class selector, and descendant selector, but is that enough?

It may not be enough. For CSS, there are still many flexible usage methods.

This article will introduce you to some common CSS selector methods, some of which are CSS3 selectors, which are only supported by newer browsers, but these new selectors should also be remembered, because old browsers like IE6 will eventually be eliminated.

OK.

1 .*
* {margin: 0;padding: 0;}

This asterisk Selects all tags on the current page. I believe many people have used this asterisk to clear the defaultmarginAndpaddingIf you use this method during testing, it will certainly be okay, but try not to use it in formal products. It is said that it will greatly increase the burden on browsers, and there is no need to clear all labels.marginAndpadding.

*It can also be used as a sub-selector:

#container * {border: 1px solid black;}

The above code will becontainerAdd a pixel-wide black solid border to all labels in the container.

2. # X
#container {width: 960px;margin: auto;}

To#The selector at the beginning allows us to select a tag Based on the ID, which is the most commonly used.IDThe selector is strictly used. For an HTML document, tags with the same ID are not allowed. Therefore, the ID selector can only select one tag.

3. X
.error {color: red;}

This is a class selector. The difference between a class selector and an ID selector is that the classes in HTML can be repeated. That is to say, the class selector can select multiple tags. When multiple tags in HTML have common features, they can be defined as a class so that they can be easily selected in CSS.

4. X Y
li a {text-decoration: none;}

This is generally called the descendant selector. For example, you only want to selectliTo use the descendant selector.

5.x
a {color: red;}ul {margin-left: 0;}

If you want to use the tag type to select all tags on the page, you can use this tag selector. For example, if you want to select all the hyperlinks on the page, you can usea { }.

6. X: visited and X: link
a:link {color: red;}a:visited {color: purple;}

This is a pseudo-class selector. We can usea:linkYou can also use:visitedTo select all the hyperlinks that have been clicked or accessed.

7. X + Y
ul + p {color: red;}

This can be called the adjacent selector. For example, the code above can only be followedulOfpTag, and onlyulThe firstpWill be selected.

8. X> Y
div#container > ul {border: 1px solid black;}

X > YAndX YThe former can only be selectedX. For example, the following tag:

<div id="container"><ul><li> List Item<ul><li> Child </li></ul></li><li> List Item </li><li> List Item </li><li> List Item </li></ul></div>

Based on the preceding HTML code,#container > ulSelect onlyidIscontainerUnder the divul, AndliThe followingulBut cannot be selected.

9. X ~ Y
ul ~ p {color: red;}

This selector andX + YThere are similarities, but there is noX + YStrictly, for the adjacent selector (ul + p).ulThe firstpLabel, andul ~ pBut you can chooseulAllpLabel.

10. X [title]
a[title] {color: green;}

This is called the attribute selector. For example, the above Code can only be used to issuetitleProperty hyperlink.

11. X [href = "foo"]
a[href="http://akasuna.com"] {color: #1f6053;}

The above CSS Code only linksHttp://akasuna.comIs set to green, while other hyperlinks are not affected. If you want to specify different colors for hyperlinks pointing to different sites, this is a good method.

12. X [href * = "akasuna"]
a[href*="akasuna"] {color: #1f6053;}

This method is more common,*=Indicates that the specified string must appear in the attribute value,Akasuna.com,Demo.akasuna.com,Bbs.akasuna.comEvenAkasuna2.comWill be selected by this selector.

13. X [href ^ = "http"]
a[href^="http"] {background: url(path/to/external/icon.png) no-repeat;padding-left: 10px;}

Some websites will display an icon next to the hyperlink to indicate this link as an external link. It is estimated that most people have seen this design. This icon is used to remind visitors, click this link to open another completely different website.

In fact, it is easy to do this, as long as you determine the starting part of the hyperlink address, if the hyperlinkhrefThe property ishttpIt indicates that it is an external link, just like the code above.

Note: What we judge here ishttpRatherhttp://First, it is unnecessary, and second, it is necessary to balancehttps://.

In addition, if this method is used, there is a premise that all internal links use relative paths rather than absolute paths, so as to ensure that internal links are nothttp.

If we want to set a specific style for those links to the hyperlink of the image, we need to determine the end Of the hyperlink address.

14. X [href $ = ". jpg"]
a[href$=".jpg"] {color: red;}

Use$Indicates the end of the string. Here we want to find the hyperlink from the link to the image, that is, the url address is.jpgThose at the end. Note: This is not taken into consideration..gifAnd.png.

15. X [data-* = "foo"]
a[data-filetype="image"] {color: red;}

Next, if we take into account all the image formats, for example:png,jpg,jpeg,gifWhat should I do? You may think of the following method:

a[href$=".jpg"],a[href$=".jpeg"],a[href$=".png"],a[href$=".gif"] {color: red;}

However, this is a bit painful and inefficient. In fact, we can use custom attributes to add an attribute for all hyperlinks pointing to images.data-filetypeSuch:

<a href="path/to/image.jpg" data-filetype="image"> Image Link </a>

Then you can use the standard selector in CSS to select these hyperlinks.

a[data-filetype="image"] {color: red;}
16. X [foo ~ = "Bar"]
a[data-info~="external"] {color: red;}a[data-info~="image"] {border: 1px solid black;}

Refer to the above 15th custom attributes, we can createdata-infoProperty. This property value can receive multiple values:

<a href="path/to/image.jpg" data-info="external image"> Click Me, Fool </a>

In this way, an attribute can express two meanings: 1. It is an external link; 2. It is a link pointing to an image. Then you can use CSS to set the style for this hyperlink separately:

/* Select the hyperlinks that contain "external" in the data-info attribute */a [data-info ~ = "External"] {color: red;}/* select the hyperlinks with "image" in the data-info attribute */a [data-info ~ = "Image"] {border: 1px solid black ;}
17. X: checked
input[type=radio]:checked {border: 1px solid black;}

It is also a pseudo-class selector, which can select the selected tags, such as single-choice and check boxes. It should be easy to use.

18. X: after

This is not a pseudo-class, but a pseudo element.:beforeLiterally, they represent the front and back of the element. In fact, their function is to add content before or after the element, and they needcontentAttribute combination, for example:

h1:after {content:url(logo.gif)}

When displayed, an image is inserted after the title content. This is a pseudo element.:after.

19. X: hover
div:hover {background: #e3e3e3;}

Come on, everyone will. It indicates the style when the mouse hangs over the element.

Note: In earlier versions of IE, this pseudo class is only valid for hyperlinks and is invalid for any other elements!

A common usage is to set a bottom border for a hyperlink when you hover your mouse over the link:

/* Order-bottom: 1px solid black; the effect looks better than text-decoration: underline; */a: hover {border-bottom: 1px solid black ;}
20. X: not (selector)
div:not(#container) {color: blue;}

Well, this pseudo-class selector is useful. If you want to selectidIscontainerFor all the Divs, this code should be what you want.

Or you want to selectpAll labels outside the tag:

*:not(p) {color: green;}

But this should be rarely used.

21. X: pseudo element
p::first-line {font-weight: bold;font-size: 1.2em;}

We can use pseudo elements (Here we use::Oh) set a style for a part of an element, such as the first line of a paragraph or the first letter. Do not, this method only applies to block-level elements.

Set the style for the first letter of a paragraph:

p::first-letter {float: left;font-size: 2em;font-weight: bold;font-family: cursive;padding-right: 2px;}

This code will be set for all sections on the pageDownThis style is often seen in newspapers.

22. X: nth-child (n)
li:nth-child(3) {color: red;}

nth-childThe pseudo-class selector uses an integer as the parameter, excluding 0, starting from 1. If you want to select 2nd of the list elements, you can useli:nth-child(2).

This method can also be used to select multiple elements, for exampleli:nth-child(4n)You can select 4th, 8th, and 12th of the list elements ...... (Multiples of 4 ).

23. X: nth-last-child (n)
li:nth-last-child(2) {color: red;}

IfulThere are 400 entries, and you only want to select the last 2nd entries. What should you do?

Comparedli:nth-child(399)For example,nth-last-child(2)It may be more suitable.

24. X: nth-of-type (n)
ul:nth-of-type(3) {border: 1px solid black;}

Sometimes, you don't want to chooseul3rdliTo select 3rdulAnd theseulNoidWhat should I do?

Usenth-of-type(n), The above Code will be the third in the pageulSet a black border of 1 pixel.

25. X: nth-last-of-type (n)
ul:nth-last-of-type(3) {border: 1px solid black;}

Refernth-last-of-typeSelf-understanding.

26. X: first-child
ul li:first-child {border-top: none;}

This pseudo class is used to select the first child element in the parent element.X:last-child. You can use it to delete the border between the first element and the last element in the list.

For example, there is a list. If each element in the list hasborder-topAndborder-bottomThen the border between the first element and the last element looks a little redundant.

Many people will think of setting a separatefirstAndlastClass name, and then clear their border through the class name. This is also possible, but the results can also be achieved by using pseudo classes. For details, see the following 27th.

27. X: last-child
ul > li:last-child {color: green;}

Andfirst-childCorresponding,last-childUsed to select the last child element in the parent element. In combination with the above 26th, the following example is provided:

HTML code

<ul><li> List Item </li><li> List Item </li><li> List Item </li></ul>

CSS code

ul {width: 200px;background: #292929;color: white;list-style: none;padding-left: 0;}li {padding: 10px;border-bottom: 1px solid black;border-top: 1px solid #3c3c3c;}

This CSS Code sets the background color for the list and eliminatesulDefault padding, and for eachliThe border is set, and the border color is deeperul.

The problem is that, as shown on the video, the top and bottom sides of the unordered list also have borders, which looks a bit uncomfortable. Next we use:first-childAnd:last-childTo solve this problem:

li:first-child {border-top: none;}li:last-child {border-bottom: none;}

Results: The border at the top and bottom ends is gone, and the problem is solved.

28. X: only-child
div p:only-child {color: red;}

In fact, you may findonly-childThis type of pseudo-class is not commonly used, but you may not use it in some cases.

only-childUsed to selectIs the unique child element in the parent element.(Only child !). For example, ifdivOnly one section is displayed in red. If multiple paragraphs exist, the Section is not affected.

See the following HTML code:

<div><p> My paragraph here. </p></div><div><p> Two paragraphs total. </p><p> Two paragraphs total. </p></div>

In this HTML code, the seconddivThere are two paragraphs, and these two selectors are not selected by this selector; and the first onedivThere is only one paragraph, so this paragraph isonly-childIt is displayed in red.

29. X: only-of-type
li:only-of-type {font-weight: bold;}

Similar to the 28th rule, child elements are selected. The difference is: the only sub-element (only one child, whether male or female) is selected in article 28th. In article 29th, select a unique element of a certain type (there can be multiple children, but the gender cannot be the same. If there are two males and one female, the only female will be selected ).

30. X: first-of-type

first-of-typeThe pseudo-class selects the first element of the same type element.

For ease of understanding, you may wish to perform a test. Copy the following code to the Text Editor:

<div><p> My paragraph here. </p><ul><li> List Item 1 </li><li> List Item 2 </li></ul><ul><li> List Item 3 </li><li> List Item 4 </li></ul></div>

At this point, if you want to use CSS to selectList Item 2What should we do?

Solution 1:

There are multiple ways to achieve the effect, first look at the first one, usefirst-of-type

ul:first-of-type > li:nth-child(2) {font-weight: bold;}

This code first findsul, Found 2ul, Select 1st, and then select 2nd in the unordered list.li.

Solution 2:

The second method is to use the adjacent selector.

p + ul li:last-child {font-weight: bold;}

FindpElementulAnd then selectulThe lastliYou can.

Solution 3:

ul:first-of-type li:nth-last-child(1) {font-weight: bold;}

Similar to solution 1, find the firstulAnd then find the lastli.

Conclusion

If you are using a low version browser such as IE 6, some of the above newer CSS selectors may not be suitable. However, you should not learn these new CSS selectors because you are using a low-version browser. If you do not learn them, you will lose yourself. Here is a browser compatibility list. You can also use Dean Edward's IE9.js to enable your earlier version of IE to support some IE9 features.

In addition, when using JS libraries such as jQuery, try to use the standard CSS3 selector instead of the custom selector of the JS library. If possible, the JS library uses the CSS parser of the browser, which is faster than the self-defined parser of the JS library.

This article is translated from The 30 CSS Selectors you Must Memorize and slightly modified. Basically, each selector has a corresponding DEMO. Check the DEMO in the original article.

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.