CSS Selectors Example

Updated on     Kisan Patel

Selectors are a way to select specific type of element from the HTML page. CSS selectors are used to select HTML elements based on their tag name, id, class, type, attribute.

The element Selector

The element selector selects elements based on the element name.

h1
{
 font-family: Arial;
 color: green;
}
h2, h3 /* We can apply style to more than one selector. */
{
 font-family: Monotype Corsiva;
 color: red;
 font-size: 28px;
}

The class Selector

You can apply style by declaring the CSS class name prefixed with “.” (period character) and setting the class attribute of the html element we can apply CSS style using the class name.

Using class selector we can assign different styles to the same element.

.RedText
{
 font-family: Monotype Corsiva;
 color: red;
 font-size: 14px;
}
.BlueText
{
 font-family: Arial;
 color: blue;
 font-size: 10px;
}

The id Selector

You can apply style by write a hash (#) character, followed by the id of the element.

#top
{
 font-family: Monotype Corsiva;
 color: blue;
 font-size: 16px;
}

You can also apply same CSS style for more than one selector, we can write the selector separated by “,” (colon) at the time of declaration.

p, .class, #id
{
font-family: Arial;
border: 1px solid silver;
}

CSS

Leave a Reply