Home >Web Front-end >HTML Tutorial >30 types of CSS selectors you must remember_html/css_WEB-ITnose

30 types of CSS selectors you must remember_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:53:511133browse

You may have read about the `id`, `class` and `descendant` selectors, and are using them all, then you are making the mistake of selecting with a greater level of flexibility. Most of the selectors mentioned in this article are under the CSS3 standard, so they can only take effect in the latest version of the corresponding browser. You should keep these in your smart mind.
1. *

Css code

  1. * {
  2. margin: 0;
  3. padding: 0;
  4. }


Before we look at more advanced selectors, we should know about this well-known clearing selection device. The asterisk will select every element on the page. Many developers use it to clear `margin` and `padding`. Of course you can use this when practicing, but I don't recommend using it in a production environment. It adds a lot of unnecessary stuff to the browser.
`*` can also be used to select all child elements of an element.

Css code

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


It will select all elements under `#container`. Of course, I still don't recommend you to use it, if possible.

DEMO
Compatibility

  • IE6
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 2. #X

    Css code

    1. #container {
    2. width: 960px;
    3. margin: auto;
    4. }


    Use `# in the selector `You can use id to locate an element. Everyone usually uses it this way, and you still have to be very careful when using it.
    You need to ask yourself: Do I have to assign an id to this element to locate it?

    The `id` selector is very strict and you cannot reuse it. If possible, try using tag names first, new elements in HTML5, or pseudo-classes.
    DEMO
    Compatibility

  • IE6
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 3. . > color: red;

    }

      This is a `class` selector. It differs from the `id` selector in that it can target multiple elements. You can use `class` when you want to style multiple elements. When you want to modify a specific element, use `id` to locate it.
    1. DEMO
    2. Compatibility
    3. IE6
    Firefox


    Chrome

    Safari

    Opera

  • 4.
  • text-decoration: none;
  • }
  • The next commonly used one is the `descendant` selector. You can use this if you want to be more specific about locating elements. For example, what if you don't need to target all `a` elements, but only the `a` tag under the `li` tag? At this time you need to use the `descendant` selector.
    Pro tip: If your selector looks like `X Y Z A B.error`, you are doing it wrong. Always remind yourself whether you really need to modify so many elements. DEMO

    Compatibility

    IE6
      Firefox
    1. Chrome
    2. Safari
    3. Opera


    5. }

    ul { margin-left: 0; }



    If you want to locate all tags on the page, not by `id` or ' class', this is simple, use the type selector directly.
  • DEMO
  • Compatibility
  • IE6
  • Firefox
  • Chrome


    Safari Opera

    6. X:visited and X:link

    Css代码 

    1. a:link {color:red;}  
    2. a:visited {color: purple;}  


    我们使用`:link`这个伪类来定位所有还没有被访问过的链接。 
    另外,我们也使用`:visited`来定位所有已经被访问过的链接。 
    DEMO 
    兼容性 

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 7. X+Y 

    Css代码 

    1. ul + p {  
    2.    color: red;  
    3. }  


    这个叫相邻选择器。它指挥选中指定元素的直接后继元素。上面那个例子就是选中了所有`ul`标签后面的第一段,并将它们的颜色都设置为红色。 
    DEMO 
    兼容性 

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 8. X>Y 

    Css代码 

    1. div#container > ul {  
    2.   border: 1px solid black;  
    3. }  


    `X Y`和`X > Y`的差别就是后面这个指挥选择它的直接子元素。看下面的例子: 

    Css代码 

    1.   
    2.    
          
      •       
      •  List Item  
      •         
            
        •            
        •  Child 
        •   
        •         
          
      •       
      •   
      •       
      •  List Item 
      •   
      •       
      •  List Item 
      •   
      •       
      •  List Item 
      •   
      •    
        


    `#container > ul` will only select all direct `ul` elements under the `div` with `id` as 'container'. It will not locate the `ul` element under the first `li`.
    For some reasons, using child nodes to combine selectors has many performance advantages. In fact, this is strongly recommended when using `css` selectors in JavaScript.
    DEMO
    Compatibility

  • IE7
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 9.

    color: red;

    }

    1. The sibling node combination selector is very similar to `X Y`, but it is not that different strict. The `ul p` selector only selects those elements that immediately follow the specified element. This selector will select all matching elements following the target element.
    2. DEMO
    3. Compatibility
    IE7

    Firefox

    Chrome

    Safari

    Opera
  • 10. ] {
  • color: green;
  • }

  • This is called an attribute selector. In the above example, only The element with the title attribute. Anchor tags that do not have this attribute will not be modified by this code. Then think again, what if you want to filter more specifically? That... DEMO

    Compatibility

    IE7
      Firefox
    1. Chrome
    2. Safari
    3. Opera


    11.
    a[href="http://strongme.cn"] {

    color: #1f6053; /* nettuts green */

    }
  • The above code will set the anchor tag whose `href` attribute value is `http://strongme.cn` to green, while other tags will not be affected.
  • Note that we enclosed the value in double quotes. Then use double quotes when using Javascript. If possible, use standard CSS3 selectors.
  • This works, but it is still a bit dead. If it is not this link, but a similar link, then you have to use regular expressions.
  • DEMO

    Compatibility

    IE7

    Firefox

    Chrome
      Safari
    1. Opera
    2. 12. 🎜>a[href*="strongme"] {
    color: #1f6053;


    }




    Tada, it’s us Required, in this way, it is specified that the value of `strongme` must appear in the `href` attribute of the anchor tag, whether it is `strongme.cn`, `strongme.com` or `www.strongme.cn`, it can be Selected.
    But remember this is a very broad expression. If the anchor tag points to a site other than `strongme` related, if you want more specific restrictions, use `^` and `$` to indicate the beginning and end of the string respectively.
    DEMO
    Compatibility

  • IE7
  • Firefox
  • Chrome
  • Safari
  • Opera

    13. 🎜>a[href^="http"] {

    background: url(path/to/external/icon.png) no-repeat;

    padding-left: 10px;
      }

    1. You must have been curious. Some sites have an external link icon next to their anchor tags. I believe you must have seen this happen. Such a design will clearly tell you that you will be redirected to another website.
      It can be easily done using the carat symbol. It is usually used in regular expressions to identify the beginning. If we want to locate the tag starting with `http` in the anchor attribute `href`, then we can use code similar to the above.

      Note that we did not search for http://, that is not necessary because it does not contain https://.

      What if we want to find all anchor tags pointing to an image? Then let's use the `&` character.
      DEMO
      Compatibility

    2. IE7
    3. Firefox
    4. Chrome
    5. Safari
    6. Opera

    7. 14. a[href$=".jpg"] {

      color: red;

      }

      1. This time we have another The regular expression `$` is used to indicate the end of the string. The meaning of this code is to search for all image links, or other links ending with `.jpg`. But remember that this way of writing will not work on `gifs` and `pngs`.
      2. DEMO
      3. Compatibility
      IE7


      Firefox

      Chrome

      Safari

    8. Opera
    9. 15.
    10. a[data-filetype="image"] {
    11. color: red;
    12. }


      Back to page Article 8, how do we select all image types `png`, `jpeg`, 'jpg', 'gif'? We can use multiple selectors. Look below:

      Css code
      1. a[href$=".jpg"],
      2. a[href$ =".jpeg"],
      3. a[href$=".png"],
      a[href$=".gif"] {


      color: red ;

      }

        But it’s very painful to write like this, and the efficiency will be very low. Another way is to use custom attributes. We can add an attribute `data-filetype` to each anchor to specify the type of image pointed to by this link.
      1. [html]
      2. Image Link
      3. Css code
      4. a[data-filetype="image"] {
      5. color: red;




      DEMO

      Compatibility

      IE7
      1. Firefox
      2. Chrome
      3. Safari
      Opera



      16. >
      Css code

    13. a[data-info~="external"] {
    14. color: red;
    15. }
    16. a[data-info~="image"] {


      border: 1px solid black; }

      I think this one will make your friends exclaim how wonderful it is. Very few people know this trick. The `~` symbol can locate tags whose attribute values ​​are multiple values ​​separated by spaces.

      Continuing with the example from item 15, we can set a `data-info` attribute, which can be used to set any space-separated value we need. For this example we will indicate them as external links and image links.
      1. Css code
      2. Click Me, Fool
      3. After setting this flag to these elements, we can use `~` to locate these tags.
      Css code


      1. /* Target data-info attr that contains the value "external" */
      2. a[data-info~="external"] {
      3. color: red;
      4. }
      5. /* And which contains the value "image" */
      6. a[data-info~="image"] {
      7. border: 1px solid black;
      8. }


      17. X:checked

      Css code

      1. input[type=radio]:checked {
      2. border: 1px solid black;
      3. }


      The above pseudo-class writing method can locate the selected radio and multi-select boxes. It is that simple.
      DEMO
      Compatibility

    17. IE9
    18. Firefox
    19. Chrome
    20. Safari
    21. Opera

    22. 18. X:after

      The two pseudo-classes `before` and `after`. It seems like every day everyone finds creative ways to use them. They generate some content around the selected tag.
      When using the `.clear-fix` technique many properties are used for the first time.

      Css code

      1. .clearfix:after {
      2. content: "";
      3. display: block;
      4. clear: both;
      5. visibility: hidden;
      6. font-size: 0;
      7. height: 0; }
      8. .clearfix {
      9. *display: inline-block;
      10. _height: 1%;
      11. }
      The above code will add a space after the target label and then clear it. For this method, you must put it in your cornucopia. This trick is particularly useful when the `overflow:hidden` method does not work.

      Want to see other creative uses of this pseudo-class, see [here](http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-getting-clever-with-css3-shadows /).

      According to the CSS3 standard, two colons `::` can be used. Then for compatibility, the browser will also accept a double quotation mark. In fact, in this case, it is more sensible to use a colon.

      Compatibility



      IE8

    23. Firefox
    24. Chrome
    25. Safari
    26. Opera
    27. 19.
      background: #e3e3e3;

      }

      Needless to say, everyone must know it. The official saying is `user action pseudo class`. It sounds a bit confusing, but it's actually okay. If you want to put some color on the place where the user's mouse hovers, then this pseudo-class writing method can do it.
      1. Note that older versions of IE will only work with the `:hover` pseudo-class added to the anchor `a` tag.
      2. Usually people use it when adding a border when the mouse hovers over an anchor link.
      Css code



      a:hover {

      border-bottom: 1px solid black;

      }

      Expert tip: border-bottom:1px solid black; looks much better than text-decoration:underline;.
        Compatibility
      1. IE6 (IE6 only works on anchor tags)
      2. Firefox
      Chrome


      Safari

      Opera

    28. 20. >
    29. p::first-line {
    30. font-weight: bold;
    31. font-size:1.2em;
    32. }



      We can use `::` to select part of a tag, such as a paragraph or the first word. But remember that it must be used on block tags to work.

      The pseudo tag is composed of two colons::.

      Positioning the first letter

      Css code

      1. p::first-letter {
      2. float: left;
      3. font-size: 2em;
      4. font-weight: bold;
      5. font-family: cursive;
      6. padding-right: 2px;
      7. }


      The above code will find all paragraphs on the page and specify them as the first of each paragraph Character.

      It is usually used to highlight the key points of the content of some news newspapers.

      Position the first line of a paragraph

      Css code

      1. p::first-line {
      2. font-weight: bold;
      3. font-size: 1.2em;
      4. }


      followed by `::first-line `Similarly, the first line of the paragraph will be selected.

      For compatibility, older browsers were also compatible with single colon writing, such as `:first-line`, `:first-letter`, `:before`, `:after`. But this one is compatible Has no effect on newly introduced features.

      DEMO
      Compatibility

    33. IE6
    34. Firefox
    35. Chrome
    36. Safari
    37. Opera

    38. 22. > li:nth-child(3) {

      color: red;

      }

      1. Remember when we faced How to get the first element of the push-pull tag? It’s a time when you have nowhere to start. With `nth-child`, those days are gone forever.
      2. Please note that `nth-child` accepts an integer parameter, and it does not start from 0. If you want to get the second element then the value you pass is `li:nth-child(2)`.
      3. We can even get the number of child tags defined by the variable name. For example, we can use `li:nth-child(4n)` to get tags for every 3 elements.
      DEMO Compatibility




      IE9

      Firefox3.5

      Chrome

      Safari

    39. 23. nth-last-child(2) {
    40. color: red;
    41. }

    42. Assume you are in an `ul` tag There are N more elements, and you only want to get the last three elements, even like `li:nth-child(397)`, you can use the `nth-last-child` pseudo-class to replace it.

      This technique can accurately replace the 16th TIP. The difference is that it starts from the end and goes back.

      DEMO

      Compatibility

      1. IE9
      2. Firefox3.5
      3. Chrome
      Safari

      Opera



      24. 🎜>
      ul:nth-of-type(3) {

      border: 1px solid black;

    43. }
    44. Once upon a time, we didn't want to select child nodes, but wanted to select based on the type of element.
    45. Imagine there are 5 `ul` tags. If you only want to modify the third one, and you don’t want to use the `id` attribute, then you can use the `nth-of-type(n)` pseudo-class to achieve it. The above code only The third `ul` tag will have a border set.
    46. DEMO
    47. Compatibility


      IE9

      Firefox3.5

      Chrome

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




      Similarly, too You can similarly use `nth-last-of-type` to get tags in reverse order.

      Compatibility

    48. IE9+
    49. Firefox3.5+
    50. Chrome
    51. Safari
    52. Opera

    53. 26. X:first-child 

      Css代码 

      1. ul li:first-child {  
      2.    border-top: none;  
      3. }  


      这个结构性的伪类可以选择到第一个子标签,你会经常使用它来取出第一个和最后一个的边框。 

      假设有个列表,没个标签都有上下边框,那么效果就是第一个和最后一个就会看起来有点奇怪。这时候就可以使用这个伪类来处理这种情况了。 
      DEMO 
      兼容性 

    54. IE7+
    55. Firefox
    56. Chrome
    57. Safari
    58. Opera

    59. 27. X:last-child 

      Css代码 

      1. ul > li:last-child {  
      2.    color: green;  
      3. }  


      跟`first-child`相反,`last-child`取的是父标签的最后一个标签。 
      例如 
      标签
       

      Css代码 

        •   
        •    
        •  List Item 
        •   
        •    
        •  List Item 
        •   
        •    
        •  List Item 
        •   
          


      这里没啥内容,就是一个了 List。 

      Css代码 

      1. ul {  
      2.  width: 200px;  
      3.  background: #292929;  
      4.  color: white;  
      5.  list-style: none;  
      6.  padding-left: 0;  
      7. }  
      8.    
      9. li {  
      10.  padding: 10px;  
      11.  border-bottom: 1px solid black;  
      12.  border-top: 1px solid #3c3c3c;  
      13. }  


      上面的代码将设置背景色,移除浏览器默认的内边距,为每个`li`设置边框以凸显一定的深度。 


       


      DEMO 

      兼容性 

    60. IE9+
    61. Firefox
    62. Chrome
    63. Safari
    64. Opera

    65. 28. X:only-child 

      Css代码 

      1. div p:only-child {  
      2.    color: red;  
      3. }  


      说实话,你会发现你几乎都不会用到这个伪类。然而,它是可用的,有会需要它的。 

      它允许你获取到那些只有一个子标签的父标签。就像上面那段代码,只有一个段落标签的`div`才被着色。 

      Css代码 

      1.  My paragraph here. 

          
      2.    
      3.   
      4.    

         Two paragraphs total. 

          
      5.    

         Two paragraphs total. 

          
      


    上面例子中,第二个`div`不会被选中。一旦第一个`div`有了多个子段落,那这个就不再起作用了。 
    DEMO 
    兼容性 

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

  • 29. X:only-of-type 

    Css代码 

    1. li:only-of-type {  
    2.    font-weight: bold;  
    3. }  


    结构性伪类可以用的很聪明。它会定位某标签只有一个子标签的目标。设想你想获取到只有一个子标签的`ul`标签? 

    使用`ul li`会选中所有`li`标签。这时候就要使用`only-of-type`了。 

    Css代码 

    1. ul > li:only-of-type {  
    2.    font-weight: bold;  
    3. }  


    DEMO 
    兼容性 

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

  • 30. X:first-of-type `first-of-type`伪类可以选择指定标签的第一个兄弟标签。 

    测试 

    Css代码 

    1.   
    2.    

       My paragraph here. 

        
    3.    
          
      •       
      •  List Item 1 
      •   
      •       
      •  List Item 2 
      •   
      •    
        
    4.    
    5.    
          
      •       
      •  List Item 3 
      •   
      •       
      •  List Item 4 
      •   
      •    
           


    Come and take out List Item 2. If you have already taken it out or gave up, continue.

    Solution 1
    There are many ways, let’s look at some of the more convenient ones. The first is `first-of-type`.

    Css code

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


    Find the first `ul` tag, then find the direct child tag `li`, then find the second child node.
    Solution 2
    Another solution is the proximity selector.
    In this case, find the immediate `ul` tag under `p`, and then find its last direct child tag.

    Solution 3
    We can play around with these selectors. Let’s take a look:

    Css code

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


    First get the first `ul` tag on the page, and then find the last sub-child Label.
    DEMO
    Compatibility

  • IE9
  • Firefox 3.5
  • Chrome
  • Safari
  • Opera

  • Conclusion

    If you want to compromise with older browsers, such as IE6, you still have to be careful when using these new selectors . But don't let IE6 stop you from learning these new skills. Then you are being cruel to yourself. Remember to check the [compatibility list](http://www.quirksmode.org/css/contents.html), or use [Dean Edward's excellent IE9.js script](http://code.google.com/p /ie7-js/) to enable your browser to have these features.

    Second, when using jQuery, try to use native CSS3 selectors. Maybe it will make your code run faster. This allows the selector engine to use the browser's native parser instead of the selector's own.

    Statement:
    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
    Previous article:Bootstrap study notes (1)_html/css_WEB-ITnoseNext article:Bootstrap study notes (1)_html/css_WEB-ITnose

    Related articles

    See more