Introduction
CSS, or Cascading Style Sheets, is a stylesheet language used to control the presentation of HTML documents. It allows you to apply styles to web pages, making them visually appealing and improving user experience. CSS handles the layout of multiple web pages all at once.
Why Use CSS?
- Separation of Content and Presentation: CSS separates the visual design of a web page from its content, which is typically written in HTML. This separation simplifies the maintenance and updating of web pages.
- Consistency: By using CSS, you can apply consistent styling across multiple pages. Changing the look of a site can be done by altering a single stylesheet.
- Improved Accessibility: CSS can enhance the accessibility of web pages, making it easier for people with disabilities to use the web.
- Better Performance: CSS can reduce the size of HTML files and improve the load times of web pages.
Basic CSS Syntax
CSS is composed of style rules that consist of selectors and declarations.
- Selector: This part of the rule selects the HTML element(s) to be styled.
- Declaration: This part of the rule describes the styles to be applied, consisting of properties and values.
Example:
h1 {
color: blue;
font-size: 24px;
}
In this example:
h1
is the selector.color
andfont-size
are properties.blue
and24px
are values.
How CSS Works with HTML
CSS can be added to HTML documents in three ways:
- Inline CSS: Using the
style
attribute within HTML elements. - Internal CSS: Using the
<style>
tag within the<head>
section of an HTML document. - External CSS: Using an external stylesheet linked via the
<link>
tag in the<head>
section of an HTML document.
Example of Inline CSS:
<p style="color: red;">This is a red paragraph.</p>
Example of Internal CSS:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: green;
}
</style>
</head>
<body>
<p>This is a green paragraph.</p>
</body>
</html>
Example of External CSS:
HTML file (index.html
):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>This is a styled paragraph.</p>
</body>
</html>
CSS file (styles.css
):
p {
color: purple;
}
Cascading and Specificity
The term "cascading" refers to the way CSS rules are applied based on their specificity and order. If multiple rules apply to the same element, the one with the highest specificity or the one defined last takes precedence.
Example:
/* External CSS */
p {
color: black;
}
/* Internal CSS */
<style>
p {
color: blue;
}
</style>
/* Inline CSS */
<p style="color: red;">This is a red paragraph.</p>
In this example, the paragraph will be red because inline CSS has the highest specificity.
Conclusion
CSS is a powerful tool for web design, enabling you to create visually appealing and consistent web pages. By understanding the basics of CSS, including its syntax and how it interacts with HTML, you can begin to harness its potential to enhance your web projects.
Toggle Sidebar