Can I use DIV class and ID together in CSS?
Can I use DIV Class and 开发者_Go百科ID together in CSS? For example:
<div class="x" id="y">
--
</div>
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 id
s are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.
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>
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 {
}
That's HTML, but yes, you can bang pretty much any selectors you like together.
#x.y { }
(And the HTML is fine too)
If you want to target a specific class and ID in CSS, then use a format like div.x#y {}
.
#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.
Yes you can.
You just need to understand what they are for, the class
is more general and can be used several times, the id
(is like your id's) you can use it only once.
This excellent tutorial helped me with that:
The Difference Between ID and Class
Though it's not an exact answer to your question I'm sure it will help you a lot!
Good luck!
EDIT: Reading your question, I just want to clarify that:
<div class="x" id="y">
--
</div>
And that if you want to "use them" in CSS for styling purposes you should do as David Says: #x.y { }
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.
Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.
精彩评论