Have a rule apply to only a particular elements by specifying those elements' class attribute and then using that class as the selector in the CSS
/* CSS */
.highlighted {
background-color: yellow;
}
<!-- HTML -->
<p class="highlighted">This text is highlighted!</p>
dot specifies class name, not tag name
A rule with a class selector will apply to any element with that class, regardless of its tag.
<!-- HTML -->
<p class="green">This text is .green!</p>
<ul>
<li class="green">This text is too!</li>
</ul>
An HTML element can have multiple classes. They are listed in the same class attribute, but separated by a space.
<!-- HTML -->
<p class="first-class second-class third-class">
This element has 3 classes
</p>
<p class="alert warning">
This element has both the .alert and .warning classes
</p>
Multiple rules can apply to the same element (in a "cascade").
p { /* applies to all paragraphs */
font-family: 'Helvetica'
}
.alert { /* applies to all elements with class="alert" */
font-size: larger;
}
.success { /* applies to all elements with class="success" */
color: #28a745; /* a pleasant green */
}
<p class="alert success">
This paragraph will be in Helvetica font, a larger
font-size, and green color, because all 3 of the above
rules apply to it.
</p>
two classes (space separated)
If two rules "conflict" (they specify different values for the same property), then the more specific rule wins.
If two rules are equally specific, the later rule wins.
Class selectors are more specific than tag selectors.
p { /* tag selector, less specific */
color: blue;
}
.husky { /* class selector, more specific */
color: purple;
}
<p class="husky">
This paragraph will be purple because the class
selector is more specifc, so overrides the other.
</p>
There are only two hard problems in computer science: cache invalidation and naming things - Phil Karlton
<div class="forum-post">...</div>
<nav class="side-nav">...</div>
<img class="avatar-icon">...</div>
<article class="breaking-news">...</article>
/* can use descendant selectors for more detail */
.forum-post img { ... }
.side-nav ul a { ... }
<div class="font-large text-red bg-secondary">...</div>
<img class="small rounded shadow">...</div>
.font-large {
font-size: 2em;
line-height: 1.4em;
}
.bg-secondary { background: #bbb; }
img.small { width: 140px; }
.rounded { border-radius: 50%; }
<div class="block__element--modifier">
<form class="form form--theme-xmas form--simple">
<input class="form__input" type="text">
<input
class="form__submit form__submit--disabled"
type="submit" />
</form>
navbar
tab
selected
<div class="navbar">
<div class="navbar__tab">A tab</div>
<div class="navbar__tab--selected">Selected Tab</div>
</div>