css - Syntax

CSS is defined as guidelines for styling HTML components. Each rule contains a selector and a declaration block.

selector {

  property: value;

}

 

Selector: Targets the HTML element(s) to style.

Property: The visual aspect to modify (e.g., color, font-size).

Value: The setting for the property (e.g., blue, 16px).

Example:

p {

  color: blue;

  font-size: 18px;

}

This rule affects all <p> elements, altering the text colour to blue and font size to 18px.

 

Types of CSS Selectors:

Type Selector: Targets elements by tag (e.g., p, h1).

Class Selector: Targets elements with a class (e.g., .classname).

ID Selector: Targets a specific element by ID (e.g., #idname).

 

Example with Multiple Properties:

h1 {

  font-family: 'Arial', sans-serif;

  color: darkblue;

  padding: 10px;

  border: 2px solid black;

  text-align: center;

}

This rule designs <h1> elements using a custom font, dark blue text, 10px padding, black border, and centered text.

 

Multiple Selectors and Grouping:

You can use the same styles for numerous selectors:

h1, h2, p {

  color: #333;

  font-family: 'Verdana', sans-serif;

}

 

This applies the same color and font to all <h1>, <h2>, and <p> elements.

 

Comments in CSS:

Comments in CSS are enclosed in /* ... */ and are ignored by browsers.

/* This is a comment */

p {

  color: green;

}

Cascading and Inheritance:

CSS prioritizes rules as follows:

Inline styles (written inside the HTML element).

Internal styles (within a <style> tag).

External styles (in a linked .css file).

Child elements inherit characteristics such as color and font-size, but not margin or padding.