Click here to Skip to main content
15,667,904 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi! I have a question about class attribute in HTML. Let's say I have two different div elements. One is classed to "Example 1".

Now, I make another, but this time I don't give it a class. Then if I go to my linked CSS stylesheet and make a declaration for div elements without specifying the class, will it apply to my classed example1 element as well, or just the non-classed one?

What I have tried:

Nothing - Hypothetical question
Updated 12-Jun-20 9:59am

1 solution

No, the style application and precedence works and that takes over which styles are applied. The class-based styles are applied to your class-based element and any div styles that are not being overridden by the class styles. On the div that does not contain a class, only div styles are applied.

Also, in CSS, styles are applied from top to bottom. So, that is also where the styles can be overridden if they are valid in the precedence.

Please see this: Specificity - CSS: Cascading Style Sheets | MDN[^] and html - What is the order of precedence for CSS? - Stack Overflow[^]

Try this example fiddle that I created and play with it to learn how the styles are applied: Edit fiddle - JSFiddle - Code Playground[^]. Code is also shared here for other purposes.
<div class="styled">
Stylized with class content.
<div> <!--Non styled-->
Non-stylized content.

The CSS for this document is:
div {
  background: #cecece;
  font-weight: 600; /* BOLD */

.styled {
  background: #fff; /* Note this change! */
	color: red;
You can see, how different properties are applied from parent type and how they are overridden by specialized class or ID (not shown here) specifiers.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900