SimpleTuts.com

CSS Selectors

Learn about element selector, id selector and class selector

1. Element Selector

The element selector targets all instances of a specified HTML element.

Example:

p { color: blue; }

This rule will apply a blue color to all <p> elements on the page.

2. ID Selector

The ID selector targets a specific element with an id attribute. Each ID must be unique within a page.

Example:

#header { background-color: yellow; }

This rule will apply a yellow background to the element with id="header".

3. Class Selector

The class selector targets elements with a specific class attribute. Multiple elements can share the same class.

Example:

.highlight { font-weight: bold; }

This rule will make the text bold for all elements with class="highlight".

Example:

HTML file


<html>
<head>
    <title>Selectors in CSS</title>
    <link rel="stylesheet" type="text/css" href="selectors.css">
</head>
<body>
    <h1 id="search">Google</h1>
    <p>This program is free software; you can redistribute it and/or modify 
    it under the terms of the <span class="gnu">GNU General Public License</span> 
    as published by the Free Software Foundation; either version 3 of the License, 
    or at your option any later version.</p>
    <h1 class="social">Facebook</h1>
    <p id="fbpara">This program is free software; you can redistribute it 
    and/or modify it under the terms of the GNU General Public License as published 
    by the Free Software Foundation; either version 3 of the License, or at your 
    option any later version.</p>
    <h1 class="social">Instagram</h1>
    <p>This program is free software; you can redistribute it and/or modify 
    it under the terms of the GNU General Public License as published by the 
    <span class="free">Free Software Foundation</span>; either version 3
    of the License, or at your option any later version.</p>
</body>
</html>
Run Code

CSS file


h1 {

    color: red;
}

hl#search {
    color: green;
    background-color: yellow;
}

hl.social {
    color: indigo;
    background-color: violet;
}

p#fbpara {
    background-color: yellowgreen;
    font-size: 20px;
}

span.gnu {
    font-size: 24px;
    background-color: aqua;
}

span.free {
    font-size: 24px;
    background-color: black;
    color: white;
}
Run Code

Watch video