CSS selector
What are the CSS selectors
We can set styles for a HTML element by using tag name as the selector. CSS supports to create our own selectors.
There are two types of selectors we can create. One is called "id" and other other is "class".
Write id selector
The id selector specifies a style for a single unique element. When applying the style we use the id attribute of the HTML element. The id select is defined with a "#".
The following CSS creates a id named para1
and sets its color.
#para1
{
color:red;
}
Let's put the id selector to work.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#myPara<!-- www .j av a2 s. c o m-->
{
text-align:center; color:red;
}
</style>
</head>
<body>
<p id='myPara'>Visit the website</p>
</body>
</html>
We use the id
attribute to add to id selector to an element.
The code above generates the following result.
Use class Selector
The class selector selects a group of elements. If we want to apply styles to a group of elements we should use class selector.
The class selector uses the HTML class
attribute, and is defined
with a ".
".
In the example below, all HTML elements with class="center"
will be center-aligned:
.center {text-align:center;}
Let's put the class selector to work.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.center {text-align:center;}<!--from ww w . j a v a 2 s . c o m-->
</style>
</head>
<body>
<p class='center'>Visit the website</p>
<p class='center'>Visit the website</p>
<h1 class='center'>Visit the website</h1>
</body>
</html>
In the code above we create a style with class selector. Then we use it with two paragraph tags and one heading tag. We can use the same style for different tags.
The code above generates the following result.
HTML Introduction
HTML Documents
HTML Element
HTML Attributes
HTML Core Attributes
HTML Comments
HTML Headings
HTML Paragraphs
HTML Rules (Lines)
HTML Line Breaks
CSS Introduction
CSS Syntax
CSS Color
CSS Lengths
CSS Comments
CSS selector
Grouping/nesting SelectorsAdd CSS to HTML
Compare em measurement and pixel measuremen...
Select class along with tag name in HTML an...
Select Next Sibling with Next Sibling Selec...
Select with Descendant Selectors in HTML an...
Set color to purple in HTML and CSS
Set color with rgb function in HTML and CSS
Set text color for body element in HTML and...
Show the difference between block and inlin...