CSS Syntax
CSS Syntax: Building Blocks
CSS relies on a specific syntax to define styles and apply them to HTML elements. Here’s a basic structure: selector { property: value; }
- Selector: This identifies the HTML element(s) you want to style. Selectors can target elements by type (e.g., h1), class (e.g., .important), or ID (e.g., #unique-element).
- Property: This specifies the aspect of the element you want to modify (e.g., color, font-size, background-color).
- Value: This assigns the desired value to the property (e.g., red, 16px, #f0f0f0).
Example:
h1 { /_ Targets all h1 elements _/color: blue;font-size: 2em;}Applying Styles to HTML Elements
There are three main ways to connect CSS styles to HTML elements:
- Inline Styles: Using the style attribute directly within the HTML element. While convenient for quick modifications, it can clutter your HTML code and hinder maintainability.
<h1 style="color: red; font-size: 2em;">This is a heading</h1>- Internal Stylesheets: Internal styles are defined within a
<style>tag in the<head>section of an HTML document. This method is useful for styling a single document.
<!DOCTYPE html><html> <head> <style> p { color: blue; font-size: 20px; } </style> </head> <body> <p>This is a paragraph.</p> </body></html>- External Stylesheets: Creating a separate .css file containing all your styles and linking it to your HTML document using the
<link>tag in the<head>section. This promotes better organization and reusability of styles.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <title>My Page</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <h1>This is a heading (styled in styles.css)</h1> </body></html>By mastering CSS syntax and applying styles effectively, you can transform the look and feel of your web pages built with HTML.