If there are two or more conflicting CSS rules that point to the same element, the browser follows some rules to determine which one is most specific and therefore wins out.
Specificity Hierarchy:
Inline styles - An inline style is attached directly to the element to be styled. Example: <h1 style="color: #ffffff;">
. (Weight = 1000)
IDs - An ID is a unique identifier for the page elements, such as #navbar
. (Weight = 100)
Classes, attributes and pseudo-classes - This category includes .classes, [attributes]
and pseudo-classes such as :hover
, :focus
etc. (Weight = 10)
Elements and pseudo-elements - This category includes element names and pseudo-elements, such as h1
, div
, :before
and :after
. (Weight = 1)
For example:
<body>
<section>
<!-- a paragraph containing class and id -->
<p class="text" id="first-line">Lorem ipsum dolor sit, amet</p>
<!-- inline styling, top priority! -->
<p style="color= green;">Lorem ipsum dolor sit, amet</p>
</section>
</body>
/* General Element, Weight: 0, 0, 1 */
p {
color: pink;
}
/* Class, Weight: 0, 1, 0 */
.text {
color: red;
}
/* ID, Weight: 1, 0, 0 */
#first-line {
color: blue;
}
/* ID + Class Weight: 1, 1, 0 */
.text#first-line {
color: blueviolet;
}
In the case above, the text color should be blueviolet
since it hold the most weight.
==Note: Be aware not to be too specific about your specificity since it may leave a mess==