CSS 2
CSS 2
Web Programming
Introduction to CSS
-CSS syntax-
Nur Fatin Nabila binti Mohd Rafei Heng
CSS syntax
• A CSS rule-set consists of
• A selector
• Points to the HTML element you want to style.
• CSS selectors are used to find (or select) HTML elements based on their element
name, id, class, and more.
• A declaration block
• Contains one or more declarations separated by semicolons (;)
• Are surrounded by curly braces ({ })
• Each declaration includes a CSS property name and a value, separated by a colon
(:)
• A CSS declaration always ends with a semicolon
CSS Selector
Element Selector ID selector Class selector
• Based on element • selector uses the id • selects elements with a
name attribute of an HTML specific class attribute.
• To select an element, element to select a • To select elements with
write the element specific element a specific class, write a
name • should be unique period (.) character
within a page
• To select an element
with a specific id, write
a hash (#) character
CSS Selector based on Element selector
• The element selector selects elements based on the element name.
• Element name- e.g. <p>, <h2>, <body>, and more.
• E.g.:
CSS Selector based on ID selector
• The id selector uses the id attribute of an HTML element to select a
specific element.
• The id of an element should be unique within a page, so the id
selector is used to select one unique element!
• To select an element with a specific id, write a hash (#) character,
followed by the id of the element.
CSS selector based on element selector CSS selector based on ID selector
Output: Output:
CSS Selector based on class Selector
• The class selector selects elements with a specific class attribute.
• To select elements with a specific class, write a period (.) character,
followed by the name of the class.
• You can also specify that only specific HTML elements should be affected by a class.
• In the example below, only <p> elements with class="center" will be center-aligned
CSS Syntax
• HTML elements can also refer to more than one class.
• In the example below, the <p> element will be styled according to
class="center" and to class="large"
CSS Syntax
Grouping Selectors
• If you have elements with the same style definitions, it will be better to group the
selectors, to minimize the code.
CSS Syntax