Introduction to CSS (Cascading Style Sheets)

CSS (Cascading Style Sheets) is a fundamental technology used for styling and designing the appearance of web pages. It works in conjunction with HTML, which defines the structure of a webpage, to enhance its visual presentation. Here's a breakdown of CSS and its key concepts:
What is CSS?
CSS is a stylesheet language used to describe the look and layout of HTML elements on a webpage. It enables developers to control various visual aspects, such as colors, fonts, spacing, positioning, and animations.
Why Use CSS?
- Separation of Content and Design: Keeps HTML structure clean by separating design-related rules.
- Reusability: Styles can be reused across multiple pages.
- Consistency: Ensures a uniform design across a website.
- Customization: Allows for the creation of visually appealing and responsive web pages.
Basic Syntax
CSS rules consist of selectors and declarations:
selector {
property: value;
}
- Selector: Specifies which HTML element(s) the rule applies to.
- Property: The visual characteristic (e.g., color, font-size).
- Value: The specific style applied to the property.
Example:
p {
color: blue;
font-size: 16px;
}
Ways to Apply CSS
-
Inline CSS: Applied directly within an HTML element using the
style
attribute.<p style="color: red;">This is a paragraph.</p>
-
Internal CSS: Written within a
<style>
tag in the<head>
section of an HTML document.<style> h1 { font-family: Arial, sans-serif; } </style>
-
External CSS: Stored in a separate file (e.g.,
styles.css
) and linked to an HTML document.<link rel="stylesheet" href="styles.css">
Types of Selectors
-
Universal Selector (
*
): Targets all elements.* { margin: 0; }
-
Type Selector: Targets elements by their HTML tag.
h1 { color: green; }
-
Class Selector (
.
): Targets elements with a specific class..highlight { background-color: yellow; }
-
ID Selector (
#
): Targets an element with a specific ID.#main { text-align: center; }
-
Group Selector: Targets multiple elements.
h1, h2, h3 { font-weight: bold; }
Box Model
CSS uses the box model to define the layout and spacing of elements. It consists of:
- Content: The actual content of the element.
- Padding: Space between the content and the border.
- Border: A boundary around the padding (if specified).
- Margin: Space outside the border, separating elements.
Example:
div {
width: 200px;
padding: 20px;
border: 2px solid black;
margin: 10px;
}
Responsive Design
CSS includes features like media queries to make websites adaptable to different screen sizes and devices.
Example:
@media (max-width: 600px) {
body {
background-color: lightgrey;
}
}
CSS is a powerful tool that enables developers to create visually appealing, consistent, and responsive designs. Mastering CSS is essential for building modern, user-friendly websites.