Skip to content

Files

Latest commit

author
Markus Bertling
Nov 28, 2016
9b64f90 · Nov 28, 2016

History

History
71 lines (63 loc) · 2.85 KB

2015-01-09-css-class-selector.markdown

File metadata and controls

71 lines (63 loc) · 2.85 KB
layout title
default
Class Selector

Class Selector

Until now we used the element selector to apply styles to an element. What’s wrong with that? Nothing, until you want to have two or more differently styled divs on your page.

Dark Light
{% highlight HTML %} <style> div { color: white; background-color: green; width: 300px; height: 200px; font-family: sans-serif; border: 5px solid black; } </style>
I am a div with a border
I am a different div but i look like the other one! 😞
{% endhighlight %}

Copy this code example into your html file, and check out what it looks like in the browser. Now let’s say the second div should be blue. We can achieve that by assigning classes to the `divs in our HTML. We can then apply styles to each class in our CSS:

Dark Light
{% highlight HTML %} <style> div { width: 300px; height: 200px; font-family: sans-serif; border: 5px solid black; }
.greenthing { background-color: green; }

.bluething {
  background-color: blue;
  font-family: serif;
  text-align: center;
}

.border-dotted { border: 5px dotted black; }
</style>
I am a div with a border
I am a different div and I don’t look like the other one any more! 😀
{% endhighlight %}

Now here you should note several things. Both divs get the styles of the div rule, as this applies to all divs. Then the first div also gets the styles of the class .greenthing. In HTML the classes get assigned by writing a class attribute inside of the opening tag of the element. The second div has two classes – you can assign as many of them as you want! Just separate them by a space. In the CSS code, class selectors are marked by a dot like this: .border-dotted. This class is remarkable as it overrides the border style that was defined in the `div selector.