Selecting Elements by Class
Description
The class selector selects elements with particular class.
- Selector: .classname or *.classname or elementType.classname
- Matches: Elements that belong to the specified class.
- Since CSS Version: 1
When used with an element type, all elements of the specified type that belong to the specified class are selected.
The selectors *.class2
and .class
are equivalent.
Example
The following code provides a demonstration of class name selector.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.class2 {<!-- ww w . j a v a 2 s . c o m-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<a class="class1 class2" href="http://java2s.com">Visit the website</a>
<p>
This is a <span class="class2">test</span>.
</p>
<a href="http://w3c.org">Visit the W3C website</a>
</body>
</html>
Example 2
The following code uses the Class Selector for a Single Element Type.
The code narrows the scope of the selector so that it will match
only span
elements that have been assigned to class2
.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
span.class2 {<!--from ww w . j a v a 2s . com-->
border: thin black solid;
padding: 4px;
}
</style>
</head>
<body>
<a class="class1 class2" href="http://java2s.com">Visit the website</a>
<p>
This is <span class="class2">a</span> test.
</p>
<a href="http://w3c.org">Visit the W3C website</a>
</body>
</html>
To select elements with multiple classes,
you can specify the class names separated with a period (e.g., span.class1.class2
).
This will select only elements that are assigned to both class1
and class2
.