CSS rules are used to define the style of HTML elements. Each rule consists of selectors and declarations. Selectors specify which elements the rule applies to, while declarations define what style properties are applied to those elements. CSS rules are written using a specific syntax, which includes selectors, declaration blocks, and property-value pairs.
selector { property1: value1; property2: value2; } .selector { property1: value1; property2: value2; }
There are several types of selectors, including element selectors, class selectors, ID selectors, and pseudo-class selectors. Element selectors apply styles to all elements of a specific type, such as all paragraphs or all headings. Class selectors apply styles to all elements with a specific class attribute, while ID selectors apply styles to an element with a specific ID attribute. Pseudo-class selectors are used to apply styles to elements based on their current state, such as when a user hovers over an element.
p { font-size: 16px; color: #333; } .title { font-weight: bold; font-size: 20px; } #header { background-color: #ccc; } a:hover { color: red; }
Declarations consist of a property and a value. The property specifies which aspect of the element's style is being defined, such as font-size or color. The value defines the specific value for that property, such as 16px or #333. Multiple declarations can be listed within the curly braces of a single rule.
CSS rules can also be combined using selectors to create more specific or complex styles. For example, multiple selectors can be used to apply a style to elements that meet certain criteria. In addition, multiple declaration blocks can be used to apply different styles to different states of an element, such as its default state and its hover state.
p, h1 { font-family: Arial, sans-serif; } .main-title, .subtitle { font-family: Georgia, serif; } #header, #footer { background-color: #ccc; } a { color: blue; text-decoration: none; } a:hover { color: red; text-decoration: underline; }