CSS (Cascading Style Sheets) is a style sheet language used for describing the presentation of a document written in HTML or XML (including XML dialects like SVG or XHTML). CSS describes how elements should be displayed on screen, in print, or spoken.
1. Basic Structure:
CSS works by associating rules with HTML elements. A CSS rule contains two main parts: a selector and one or more declarations. Declarations consist of a property and a value, separated by a colon, and are terminated by a semicolon. For example:
selector {
property: value;
}
2. Selectors:
Selectors are patterns used to select the elements you want to style. They can target HTML elements, classes, IDs, attributes, or combinations of these. Some common selectors include:
- Element Selector: Targets HTML elements directly, like
p
for paragraphs. - Class Selector: Targets elements with a specific class, like
.example
. - ID Selector: Targets elements with a specific ID, like
#header
. - Attribute Selector: Targets elements with a specific attribute value, like
[type="text"]
.
3. Properties and Values:
CSS properties define the visual appearance of an element. There are hundreds of CSS properties available, covering everything from colors and fonts to layout and animations. Some common properties include:
color
: Sets the color of text.font-family
: Defines the font family for text.font-size
: Sets the size of text.background-color
: Sets the background color of an element.border
: Defines the border of an element.padding
: Sets the padding inside an element.margin
: Sets the margin outside an element.
4. Cascading and Specificity:
CSS stands for Cascading Style Sheets, which means styles can cascade from one rule to another. If multiple rules apply to the same element, the most specific rule takes precedence. Specificity is determined by the combination of selectors used. For example, an ID selector (#header
) is more specific than a class selector (.container
).
5. Linking CSS to HTML:
You can link an external CSS file to your HTML document using the <link>
element within the <head>
section:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
</body>
</html>
Alternatively, you can include CSS directly within your HTML file using the <style>
element:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
</body>
</html>
6. Inline Styles:
You can also apply styles directly to HTML elements using the style
attribute:
<p style="color: blue;">This is a blue paragraph.</p>
While inline styles are convenient, it's generally recommended to separate your CSS from your HTML for better organization and maintainability.
CSS is a powerful tool for controlling the visual presentation of web pages, allowing developers to create layouts, apply colors and fonts, and add interactive effects to enhance the user experience.