CSS Selectors
How To Apply CSS Styles To A Specific HTML Element
When applying css styles to an html element inline its pretty obvious which element is going to get the style transformation. If however you want to flex the full muscle of CSS you need to separate it from your html and define it in an external style sheet, or at least in the head of the html file so that you can make your changes from one easy to get to location.
To do so you need to know how to tell the browser which element you want to apply which styles to.
Lets look at the basic format (syntax) of CSS style declaration.
CSS Code:
SELECTOR { PROPERTY : VALUE;}
Selectors
There are three ways with which you can select an html element to apply a style to. They are:
- By Tag Name
- By Class Name
- By Identifier Name
By Tag Name
You can apply CSS styles to all occurances of an html element that appear in a page by using the tag name as the selector.
CSS Code:
body { text-align : center; color: #00f;}
p {font-weight : bold; font-size : .9em}
In this case everything in the body tag will have the text centered and colored blue. Every paragraph tag will have bold text and be .9em in size.
By Class Name
You can apply css styles to specific elements that you gave a class name to in your html files with the "class" attribute. This allows you to group together elements to be displayed with a certain style.
To apply CSS styles to a specific class you specify the class name preceded by a dot(.) as the selector.
CSS Code:
.right { text-align : right;}
.clear_b {clear : both;}
By Identifier Name
You can apply css styles directly to an html element within a web page by specifying the identifier name that was defined in the html with the "id" attribute preceded by a pound sign(#).
CSS Code:
#intro { font-weight: bold;}
#footer {clear : both; float : right;}
Note: Remember that an "id" name is specific and should only be applied to one html element per page, whereas a "class" name can be applied to numerous elements on a html page.
Combinations
You can get pretty specific when applying CSS declarations. You can combine the 3 previous examples to gain deep control of your html display. For example:
If you wanted all paragraphs within a div element that is defined by the class name "first" to have blue large text and wanted to make an unordered list with an id of "top_nav" display horizontally instead of vertically you could do so like:
CSS Code:
.first p { font-size: bigger;}
#top_nav li {display : inline; float : left;}