How do I select an element that has a certain class?

后端 未结 5 1329
清歌不尽
清歌不尽 2020-12-04 15:14

My understanding is that using element.class should allow for a specific element assigned to a class to receive different \"styling\" than the rest of the class

相关标签:
5条回答
  • 2020-12-04 15:29

    h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

    Your want to note it like this:

    .myClass h2
    

    Which selects all children of myClass which have the tagname h2

    0 讨论(0)
  • 2020-12-04 15:31

    h2.myClass refers to all h2 with class="myClass".

    .myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

    If you want the h2 in your HTML to appear blue, change the CSS to the following:

    .myClass h2 {
        color: blue;
    }
    

    If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

    <h2 class="myClass">This header should be BLUE to match the element.class selector</h2>
    
    0 讨论(0)
  • 2020-12-04 15:38

    The element.class selector is for styling situations such as this:

    <span class="large"> </span>
    <p class="large"> </p>
    
    .large {
        font-size:150%; font-weight:bold;
    }
    
    p.large {
        color:blue;
    }
    

    Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

    As others have pointed out, what you're working with is descendant selectors.

    0 讨论(0)
  • 2020-12-04 15:46

    The CSS :first-child selector allows you to target an element that is the first child element within its parent.

    element:first-child { style_properties }
    table:first-child { style_properties }
    
    0 讨论(0)
  • 2020-12-04 15:55

    It should be this way:

    h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

    h2 {
        color: red;
    }
    
    .myClass {
        color: green;
    }
    
    .myClass h2 {
        color: blue;
    }
    

    Demo

    This ref will give you some basic idea about the selectors and have a look at descendant selectors

    0 讨论(0)
提交回复
热议问题