I would like to make both the h2 and link white, which is easy enough, but I also have another type of block that exists outside the overlay where I would like a h2 to be white... what is the best way to go about this?
For your specific case, it sounds like the best way to write the code would be:
// in overlay.css/.less/.scss/etc...
.overlay__title,
.overlay__text{
color: white;
}
// in otherBlock.css/.less/.scss/etc...
.otherBlock__title{
color: white;
}
Which looks oddly familiar.
To explain why, lets take a step away from CSS and look at how other programming languages work.
Imagine you have an object in an OOP language, such as C#, and that object is supposed to represent a book. The book object will probably need a title
(e.x. Hitchhiker's Guide to the Galaxy):
class Book {
string Title { get; set; }
}
Now imagine that you now need to create an object that represents a person. The person object will also need a title
(e.x. Dr.):
class Person {
string Title { get; set; }
}
Between these two classes there is no inheritance structure. This means that there will be some code that needs to get rewritten, despite looking similar.
Going back to CSS, these two blocks happen to have some similar styles. You haven't described any sort of relation between the two that they should leverage for code reuse, so simply duplicate the styles.
If you use a preprocessor, you may find that it's useful to use variables—particularly for colors—and mixins—particularly for chunks of reusable styles—to reduce the amount of code you actually write, but in the end the CSS will be moderately repetitious.
This is fine. If your CSS gets served gzipped, then duplication will compress quite well.
...but what about other cases?
If you find that you're constantly overriding a particular set of styles (.body__text
, .content__text
, .description__text
) and they all refer to the same element (e.x. <p>
), then consider updating your default styles for that element to reduce the amount of CSS you're using to override the element.
If you find that you're constantly rebuilding the same particular structure within existing blocks, you may need to create a new block. For example:
<div class="article">
<time class="article__timestamp">
<span class="article__date">...</span>
<span class="article__time">...</span>
</time>
...
</div>
and
<div class="post">
<time class="post__timestamp">
<span class="post__date">...</span>
<span class="post__time">...</span>
</time>
...
</div>
might be refactored to:
<div class="article">
<time class="timestamp">
<span class="timestamp__date">...</span>
<span class="timestamp__time">...</span>
</time>
...
</div>
and
<div class="post">
<time class="timestamp">
<span class="timestamp__date">...</span>
<span class="timestamp__time">...</span>
</time>
...
</div>