Lesson 1: Introduction to CSS
Understanding Cascading Style Sheets
In this lesson, we'll dive into the fundamentals of CSS and its role in web development. CSS allows us to control the presentation and layout of HTML elements, enhancing the visual appeal and usability of webpages.
CSS Syntax
CSS consists of rulesets that define how HTML elements should be styled. Each ruleset includes a selector and one or more declarations.
Anatomy of a CSS Ruleset:
```css
selector {
property: value;
/ More properties and values /
}
```
- Selector:
Specifies the HTML elements to which the styles should be applied.
- Property:
Describes the aspect of the element to be styled, such as color, font size, or margin.
- Value:
Specifies the value of the property, such as specific colors or sizes.
CSS Selectors
CSS selectors determine which HTML elements will be affected by the styles defined in the ruleset. There are various types of selectors, including:
1. Element Selector:
Targets HTML elements by their tag name.
2. Class Selector:
Targets HTML elements by their class attribute.
3. ID Selector:
Targets HTML elements by their ID attribute.
4. Attribute Selector:
Targets HTML elements based on their attribute values.
Example: CSS Ruleset
Let's create a simple CSS ruleset to style a paragraph element:
`
``css
/ CSS Stylesheet /
p {
color: blue;
font-size: 16px;
}
```
In this example:
- `p` is the selector targeting all paragraph elements.
- `color` and `font-size` are properties.
- `blue` and `16px` are values assigned to the properties.
Linking CSS to HTML
To apply CSS styles to HTML elements, we need to link our CSS stylesheet to our HTML document using the `<link>` element.
Example: Linking CSS to HTML
```html <!DOCTYPE html> <html> <head> <title>My Website</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <p>This is a paragraph styled with CSS.</p> </body> </html> ```
Explanation
CSS is essential for controlling the visual presentation of HTML elements on webpages. By understanding CSS syntax, selectors, and how to link CSS to HTML documents, you'll have the foundation needed to create stunning and responsive web designs.
Exercise
Practice creating CSS rulesets to style HTML elements. Experiment with different properties, values, and selectors to understand how they affect the appearance of web content.