CSS

2.7 Span and Class

Contents

Overview

To change the way your HTML elements appear, you simply use the HTML element as the selector in CSS:



h1{
    color:blue;
}

So what do we do when we want to alter the way something displays but there is no element surrounding it? For example, if we want to make one word in a sentence a different color.

We use the <span> element. It offers no semantic information about the content inside and provides no styling change, or any other visual change. When you wrap text with an opening <span> and closing </span>, you’re simply providing a hook — one that allows you to add styles for CSS.

How To

  1. In HTML, use a <span> element to surround the text:
  2. 
    
    <p>If your canoe is stuck in a tree with the headlights on, how many <span>pancakes</span> does it take to get to the moon?</p>
    
    
  3. In HTML, attach a class attribute to the <span>. Be sure to use a class name value that makes sense (e.g. since I’m changing the text to red, I’m using “red-text”):
  4. 
    
    <p>If your canoe is stuck in a tree with the headlights on, how many <span class="red-text">pancakes</span> does it take to get to the moon?</p>
    
    
  5. In your CSS file, use this syntax for your declaration. Notice that the selector has a period (.) in front of it. We use this syntax when referring to class names we create:
  6. 
    
    .red-text{
        color:red;
    }
    
    

Save both files and reload.

Using Classes

Follow these rules when creating your class name values:

Re-use your classes. If you have more than one thing you are changing using the same properties, be sure to re-use that class in your HTML:



<p>If your canoe is stuck in a <span class="red-text">tree</span> with the headlights on, how many <span class="red-text">pancakes</span> does it take to get to the moon?</p>

Classes can be attached to any element. For example, if you only wanted to change a property of one paragraph, you would attach the class to the <p> in HTML:



<p class="larger-text">This is just one paragraph of text.</p>

Do this when you just want to change one (or one set) of something. Again, you can use a class with any element.



<li class="whatever"></li>
<img class="whatever"... />
<a class="whatever"... ></a>