Thursday, January 5, 2012

Understanding Cascading Style Sheets (CSS) Selectors

Without selectors, CSS properties cannot be applied. As basic knowledge of a Cascading Style Sheets (CSS), selectors are used to select elements or tags, classes and id's inside HTML page so that they can be styled.

Note: # selects id and . selects class


Example 1. Select all a tag under id of footer, and set color to green.

Syntax
#footer a {
  color:green;
}
Description
Selector Property Value
#footer a color green
HTML
<div id="footer">
  <ul>
    <li><a href="#">about</a></li>
    <li><a href="#">contact</a></li>
    <li><a href="#">help</a></li>
  </ul>
</div>
Example 2. Select h1 tag having class of small, and set font-size to 17px.

Syntax
h1.small {
  font-size:17px;
}
Description
Selector Property Value
h1.small font-size 17px
HTML
<div id="content">
  <h1>Welcome!</h1>
  <h1 class="small">to my website</h1>
  <p>Let's talk about css selectors</p>
</div>
CSS Rule Specificity

In CSS the more specific the selector, the higher precedence it has.

Below, the first rule selects all h1 tag, and set font-size to 35px. But the second rule selects specifically h1 having class of small, that sets font-size into a value of 17px. So, h1.small selector is more specific than h1, as result, it overrides font-size: 35px and use font-size: 17px.
h1 {
  font-size:35px;
  color: blue;
}
h1.small {
  font-size:17px;
}
HTML and CSS Example

Here's a quick and simple html which is based on examples above that you can practice and explore CSS using selectors you want.
<!DOCTYPE html>
<html>
<head>
<title>CSS Selector</title>
<style type="text/css">
/* --- css here --- */
</style>
</head>
<body>
<div id="nav">
  <ul>
    <li><a href="#">about</a></li>
    <li><a href="#">contact</a></li>
    <li><a href="#">help</a></li>
  </ul>
</div>
<div id="content">
  <h1>Welcome!</h1>
  <h1 class="small">to my website</h1>
  <p>Let's talk about css selectors</p>
</div>
<div id="footer">
  <ul>
    <li><a href="#">about</a></li>
    <li><a href="#">contact</a></li>
    <li><a href="#">help</a></li>
  </ul>
</div>
</body>
</html>

No comments:

Post a Comment