codescracker


css

CSS Syntax



« Previous Tutorial Next Tutorial »


Syntax can be defined as a rule that defines the structure or the order of the statements used in a programming language. It also specifies how words and symbols are put together to form statements and expressions.

CSS also uses syntax to apply CSS rules in an HTML document.

The CSS syntax is divided into two the following different parts.

Selectors defines an HTML element to which the CSS style is applied and the declaration contains the CSS properties as well as the value of these properties.

The following code fragment shows the syntax of a CSS document.

Selector
{
	1st property : value;
	2nd property : value;
	3rd property : value;
	.
	.
	.
	Nth property : value;
}

The preceding syntax consists of a selector and CSS properties with their values. The selector is the name of the element to which you want to apply the CSS properties.

You can put CSS Style Rule Syntax as follows:

selector { property: value }

The following code fragment is used to create a CSS file.

span
{
	background:#fff;
	padding:0 3px 0 0;
	float:left;
	position:absolute;
	text-decoration:none;
}
ol
{
	list-style:lower-roman;
	margin:1.5em 0 1em 5%;
	padding:0;
	background:#fff;
	float:left;
	display:block;
	width:95%;
}
a
{
	padding:0 0 0 3px;
	right:0;
}
li
{
	clear:left;
	border-bottom:dashed 1px #aaa;
	height:1.05em;
	margin-top:10px;
	position:relative;
}

In the above code fragment, span, ol, a, and li are the four different selectors of a CSS file. The span selector has properties, such as background, padding, float, position, and text-decoration.

Each property is assigned with its corresponding values, for example, the background property has #fff as value while the value of the padding property is 0 3px 0 0. Similarly, all the selectors have their corresponding properties with each property having its corresponding value.

CSS Syntax Example

A CSS declaration always ends with a semicolon, and declaration groups are surrounded by curly braces:

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

Here p is the selector, color is the property and red is the value.

To make the CSS code more readable, you can put one declaration on each line.

Look at the following example where all the <p> elements will be center-aligned, with a red text color.

<!DOCTYPE html>
<html>
<head>
	<title>CSS Syntax Example</title>
	<style>
		p
		{
			color: red;
			text-align: center;
		}
	</style>
</head>
<body>

<p>Hello Browser!</p>
<p>I am center-aligned with red color.</p>

</body>
</html>

Here is the sample output produced by the above CSS syntax example code:

CSS Syntax Example

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test