CSS (Cascading Style Sheets)
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. It controls the look and feel of a web page by defining styles such as fonts, colors, layouts, and spacing. CSS separates content (HTML) from presentation, allowing for greater flexibility in web design and easier maintenance.
With CSS, developers can apply specific styles to elements either globally or locally, and it supports responsive design, ensuring web pages look good on various devices, including smartphones and tablets. It allows the use of selectors, classes, and IDs to target HTML elements for styling.
CSS works in a cascade system, where multiple rules can apply to a single element, and priorities are determined based on the specificity of selectors and rule order.
How to Apply CSS
There are three ways to apply CSS to HTML documents:
- Inline CSS
- Internal CSS (in the <style> tag)
- External CSS (linking a separate .css file)
Inline CSS
Inline CSS is used to apply a unique style to a single HTML element. Use the style attribute inside the HTML element.
<p style=”color: blue; font-size: 20px;”>This is a blue paragraph.</p>
Internal CSS
Internal CSS is used to define a style for a single HTML page. It is defined in the <head> section inside a <style> element.
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
font-size: 18px;
}
</style>
</head>
<body>
<p>This is a red paragraph.</p>
</body>
</html>
External CSS
External CSS is used to define the style for multiple HTML pages. An external style sheet can be written in any text editor and must be saved with a .css extension. The external .css file is then linked to the HTML document using the <link> tag.
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”styles.css”>
</head>
<body>
<p>This is a paragraph styled by an external stylesheet.</p>
</body>
</html>
In styles.css
p {
color: green;
font-size: 16px;
}
Basic CSS Syntax
CSS is written in a specific syntax. A CSS rule consists of a selector and a declaration block.
selector {
property: value;
property: value;
}
Example
p {
color: blue;
font-size: 20px;
}
In this example, p is the selector, and color: blue; and font-size: 20px; are the declarations.
Comments in CSS
Comments in CSS are used to add notes or explanations within the code. These comments are not rendered by the browser and do not affect the visual output of the CSS. They are purely for developers to make the code more readable or to leave notes for future reference.
CSS comments start with /*
and end with */