Can I use DIV class and ID together in CSS?

后端 未结 9 1356
名媛妹妹
名媛妹妹 2020-12-25 10:21

Can I use DIV Class and ID together in CSS? For example:

--
相关标签:
9条回答
  • 2020-12-25 10:26

    #y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

    0 讨论(0)
  • 2020-12-25 10:34

    Yes, yes you can.

    #y.x {
     /* will select element of id="y" that also has class="x" */
    }
    

    Similarly:

    .x#y {
     /* will select elements of class="x" that also have an id="y" */
    }
    

    Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since ids are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.

    0 讨论(0)
  • 2020-12-25 10:35

    Of course you can.

    Your HTML there is just fine. To style the elements with css you can use the following approaches:

    #y {
        ...
    }
    
    .x {
        ...
    }
    
    #y.x {
        ...
    }
    

    Also you can add as many classes as you wish to your element

    <div id="id" class="classA classB classC ...">
    </div>
    

    And you can style that element using a selector with any combination of the classes and id. For example:

    #id.classA.classB.classC {
         ...
    }
    
    #id.classC {
    }
    
    0 讨论(0)
  • 2020-12-25 10:44

    You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.

    <p id="unique" class="x y z">Styled paragraph</p>
    
    0 讨论(0)
  • 2020-12-25 10:47

    Yes, in one single division you can use both but it's not very common. While styling you will call both so it will cause some ambiguity if you don't properly choose "x" and "y". Use # for ID and . for class. And for overall division you will either do separate styling or write: #x .y for styling purposes.

    0 讨论(0)
  • 2020-12-25 10:48

    If you want to target a specific class and ID in CSS, then use a format like div.x#y {}.

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