X
HOME HTML5 CSS3 JAVASCRIPT SQL PHP5 JQUERY ANGULAR BOOTSTRAP3 XML MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

CSS Selectors


CSS Selectors

CSS selectors allow you to select and manipulate HTML element(s).

CSS selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more.


The element Selector

The element selector selects elements based on the element name.

You can select all <p> elements on a page like this: (all <p> elements will be center-aligned, with a red text color)

Example

p {
    text-align: center;
    color: red;
}

Try it yourself »


The id Selector

The id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the id selector when you want to find a single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the element.

The style rule below will be applied to the HTML element with id="para1":

Example

#para1 {
    text-align: center;
    color: red;
}

Try it yourself »

Note Do NOT start an ID name with a number!


The class Selector

The class selector finds elements with the specific class.

The class selector uses the HTML class attribute.

To find elements with a specific class, write a period character, followed by the name of the class:

In the example below, all HTML elements with class="center" will be center-aligned:

Example

.center {
    text-align: center;
    color: red;
}

Try it yourself »

You can also specify that only specific HTML elements should be affected by a class.

In the example below, all p elements with class="center" will be center-aligned:

Example

p.center {
    text-align: center;
    color: red;
}

Try it yourself »

Note Do NOT start a class name with a number!


Grouping Selectors

In style sheets there are often elements with the same style:

h1 {
    text-align: center;
    color: red;
}

h2 {
    text-align: center;
    color: red;
}

p {
    text-align: center;
    color: red;
}

To minimize the code, you can group selectors.

To group selectors, separate each selector with a comma.

In the example below we have grouped the selectors from the code above:

Example

h1, h2, p {
    text-align: center;
    color: red;
}

Try it yourself »



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB HOSTING

UK Reseller Hosting

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE

facebook