CSS (Cascading Style Sheets) is a powerful styling language used to control the presentation of HTML documents. In this tutorial, we will cover the basic syntax of CSS and how to apply styles to HTML elements.
A CSS rule consists of a selector and a declaration block. The selector targets the HTML element(s) to which the styles will be applied, and the declaration block contains one or more property-value pairs enclosed in curly braces.
Example
selector {
property1: value1;
property2: value2;
}
CSS selectors are used to target specific HTML elements. Here are some commonly used selectors
<h1>Heading 1</h1>
h1 {
color: blue;
font-size: 24px;
}
<div class="container">
<h2>Title</h2>
<p>Content</p>
</div>
.container {
background: red;
}
<h1 id="my-heading">This is a heading</h1>
#my-heading {
color: red;
}
<input type="text" name="username">
input[type="text"] {
border: 1px solid red;
color: blue;
}
CSS properties define the aspect of an element that you want to style, and values specify the specific styling for that property. Here are a few examples:
element {
color: blue;
font-size: 24px;
background-color: red;
margin: 2px;
}
CSS follows a cascading order of styles, where multiple rules can target the same element. The specificity of the selectors determines which styles take precedence. Inline styles have the highest specificity, followed by IDs, classes, and element selectors.
CSS allows you to add comments to your code for documentation or explanation purposes.
/* This is a single-line comment */
/*
This is a multi-line comment.
You can add multiple lines of comments here.
*/
You can import external CSS files into your HTML document using the <link> element or the @import rule. This allows you to organize your CSS code into separate files for easier management.
Example
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to my website!</h1>
<p>This is some text.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
@import url('styles.css');
</style>
</head>
<body>
<h1>Welcome to my website!</h1>
<p>This is some text.</p>
</body>
</html>