Avoid Using Inline Styles

Combining Classes

Furthermore, you can apply multiple classes to elements, just by separating them with a space. So you wanted the first item to be bold, and the third to be underlined, you could do this:

<div class="sheet">
    <div class="bio">
        <span>Name</span>
        <input type="text" name="attr_name" value="">
    </div>
    <div class="stat">
        <span>Score</span>
        <input type="number" name="attr_score" value="10">
    </div>
</div>Code language: JavaScript (javascript)

And create extra CSS styles to make that happen:

.bold {
   font-weight: bold;
}
.underline {
   text-decoration: underline;
}Code language: CSS (css)

And then anywhere in your document, if you wanted to make text bold or underlined, or both, you can just add those classes:

<span class="bold underline">Attribute</span>Code language: HTML, XML (xml)

By creating classes like these, just once, you can reuse them and reapply them wherever you want.

Inheriting Classes

One final benefit to using classes over inline styles is the way they pass down through the HTML structure.

If you don’t know, HTML has a hierarchy – things nested inside each other. For example:

<div class="sheet">
    <div class="bio">
        <span>Name</span>
        <input type="text" name="attr_name" value="">
    </div>
    <div class="stat">
        <span>Score</span>
        <input type="number" name="attr_score" value="10">
    </div>
</div>Code language: HTML, XML (xml)

Here we have a div named sheet, that contains two divs. The first inner div is called bio and has a place for the character’s name. The second is called stat and has a place for the character’s stat score.

It’s easy to imagine the bio contains other values, like a description, gender, and so on. Likewise, the stat div might contain several stats.

Let’s say you want to change all the spans inside stat to bold. You could easily do this by taking advantage of the sheet’s hierarchy:

div.stat span {
   font-weight: bold;
}Code language: CSS (css)

When elements are separated by a space, it means “look inside”, or “nested inside of”. So this means, “all spans nested inside of divs with a class of stat”. So if there were multiple spans inside that stat, they would all be made bold.

But even better, you can “miss” levels. Look at this:

div.sheet span {
   font-weight: bold;
}Code language: CSS (css)

This targets all spans inside the div classed sheet, no matter whether they are inside divs further down. So this would affect all spans inside the bio and stat divs.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.