Core tips: CSS rules consist of two main parts: selectors, and one or more declarations.
CSS syntax
CSS rules consist of two main parts: selectors, and one or more declarations.
selector {declaration1; declaration2;. Declarationn}
Selectors are usually HTML elements that you need to change the style.
Each declaration consists of a property and a value.
property is the style attribute that you want to set. Each property has a value. Property and value are separated by colons.
selector {Property:value}
The following line of code defines the color of the text within the H1 element as red and sets the font size to 14 pixels.
In this example, H1 is the selector, color and font-size are attributes, red and 14px are values.
h1 {color:red; font-size:14px;}
The following diagram shows you the structure of the above code:
Tip: Use curly braces to surround the declaration.
Different ways and units of values
In addition to the English word red, we can also use the hexadecimal color value #ff0000:
#ff0000
; }
To save bytes, we can use the abbreviated form of CSS:
#f00
; }
We can also use RGB values in two ways:
rgb(255,0,0)
; }
rgb(100%,0%,0%)
; }
Note that when you use the RGB percentage, the percent symbol is written even when the value is 0 o'clock. But in other cases it doesn't have to be. For example, when the size is 0 pixels, the PX unit does not need to be used after 0, because 0 is 0, regardless of the unit.
Remember to write quotes
Tip: If the value is a number of words, enclose the value in quotes:
"sans serif"
;}
Multiple declarations:
Tip: If you want to define more than one declaration, you need to separate each declaration with a semicolon. The following example shows how to define a centered paragraph with a red text. The last rule is that you do not need a semicolon, because the semicolon is a separator in English, not a closing symbol. However, most experienced designers will have semicolons at the end of each statement, so the advantage is that when you add or subtract a declaration from an existing rule, you minimize the likelihood of error. Just like this:
p {text-align:center ;
color:red;
You should only describe one attribute per line, which will enhance the readability of the style definition, like this:
p {
text-align:center;
Color:black;
font-family:arial;
}
Spaces and uppercase and lowercase
Most style sheets contain more than one rule, and most rules contain more than one declaration. The use of multiple declarations and spaces makes it easier to edit a style sheet:
Body {
color: #000;
Background: #fff;
margin:0;
padding:0;
Font-family:georgia, Palatino, serif;
The inclusion of spaces does not affect how CSS works in the browser, and, unlike XHTML, CSS is insensitive to capitalization. There is an exception: class and ID names are sensitive to capitalization if they involve working with HTML documents.