Selecting Elements by Class

The class selector selects elements with a particular class. The class is defined by using the class global attribute.

Syntax:

 
.<classname>
  

or

 
<elementType>.<classname>
  
 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        .class1 { 
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <a class="class1" href="http://java2s.com">Visit the java2s.com</a> 
        <a href="http://java2s.com">Visit the website</a> 
    </body> 
</html>
  
Click to view the demo

The selectors *.class2 and .class are equivalent.

Using the Class Selector for a Single Element Type:

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        span.class1 { 
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <a class="class1" href="http://java2s.com">Visit the java2s.com</a> 
        <p>I like <span class="class1">HTML</span> and CSS.</p> 
        <a href="http://java2s.com">Visit the website</a> 
    </body> 
</html>
  
Click to view the demo
Home 
  HTML CSS Book 
    CSS  

Selectors:
  1. Selecting All Elements
  2. Selecting Elements by Type
  3. Selecting Elements by Class
  4. Selecting Elements by ID
  5. Selecting Elements by Attribute
Related: