CSS CSS Basics (2014) Basic Selectors Reusing Classes

Damien Watson
Damien Watson
27,419 Points

Reusing Classes vs Defining properties

Apologies for the title, I didn't know how to explain in a few words. My question is 'should you reuse classes or define all the properties for a specific element'? ... e.g.

<div id="container1" class="left round t-border"></div>
<!-- vs -->
<div id="container2"></div>
  #container2  { float:left;
                 border-radius:5px;
                 border-top:1px solid #CCC; }
  .left        { float:left; }
  .border      { border-radius:5px; }
  .t-border    { border-top:1px solid #CCC; }

I understand the thought process around defining basic classes to be reused through html, but doesn't this mean you have to go back and change the html to adjust styles later?

This can be an issue when your front end code is being implemented into a CMS that you have no control over apart from CSS.

Thoughts? Thanks. :)

2 Answers

Hi Damien,

This gets at a fundamental design philosophy that I struggle with a lot - and usually end up using both. The core question to answer, as I understand it, do you want the HTML to descriptively convey to the reader what styles are being applied, or should classes describe what these blocks of elements represent.

For example, if you use Bootstrap, your HTML elements can have several classes that all build upon each other and mean special style rules in certain combinations - I like to think of this as magic, because it's not intuitive until you crack open the source code (even then it can be confusing).

Conversely, there are many developers who firmly believe that classes should describe what the element is and hide styling decisions in the CSS file. This is a long way of saying it's personal preference and for readability, whichever style you go with, try and stay consistent - consistency enables predictability.

For what it's worth, I have noticed that it's common to use JavaScript / jQuery to add or remove classes on events. These class names often describe the style being applied.

.float-left {
  float: left;
}
Damien Watson
Damien Watson
27,419 Points

Hi Robert, I have been doing this for a while but the majority of time I have been the only Front End Dev, so not able to check what others do. The adding specific classes via jQuery does make sense.

I will probably stick with defining a main class per item, allowing control through css. Thank you for your time.

Hey ! yeah right, for that kind of issues when not having any access to the html file, you have pseudo classes, and adjecent classes , you ll know that in the course of CSS SELECTORS.