CSS uses selectors to select HTML element(s) and adds styles.
CSS selectors can select HTML elements based on their id, classes, types, attributes, values of attributes and much more.
You can select all of the instances of an element using the element type as the selector.
The following code adds border and paddings to all anchor elements.
a { border: thin black solid; padding: 4px; }
The ID selector selects elements by the id
attribute.
The value of an element's id attribute must be unique within the HTML document.
The ID selector is looking for a single element.
The following code selects element whose id is myAnchor
.
#myAnchor { border: thin black solid; padding: 4px; }
The class selector selects elements with particular class.
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.
The following code selects all elements whose class is class2
.
.class2 { border: thin black solid; padding: 4px; }
We can also uses the Class Selector for a Single Element Type.
We can further narrows the scope of the selector so that it will match
only span
elements that have been assigned to class2
.
span.class2 { border: thin black solid; padding: 4px; }
Grouping Selectors can add style for several selectors.
To group selectors, separate each selector with a comma.
Suppose we have the following style:
h1 { text-align: center; color: red; } h2 { text-align: center; color: red; } p { text-align: center; color: red; }
In the example below we have grouped the selectors from the code above:
h1, h2, p { text-align: center; color: red; }