Introduction to CSS


CSS Tutorials

CSS (Cascading Style Sheets) is a styling language used to control the presentation and layout of web documents. In this tutorial, we’ll cover the basics of CSS, including how to apply styles to HTML elements using CSS rules.

1. Linking CSS to HTML:

CSS is applied to HTML documents using either external style sheets or internal styles. Let’s start with an internal style within an HTML document.

<!DOCTYPE html> <html lang="en">
 <head> <title>My First CSS Page</title> 
 <style> 
 h1 { 
 color: blue; 
 font-family: Arial,
  sans-serif; 
  } 
 </style> 
 </head> 
 <body> 
 <h1>Hello, CSS!</h1> 
 </body> <
 /html>
  • The <style> tag is placed in the <head> section of the HTML document.
  • Inside <style>, we define CSS rules. Here, we select all <h1> elements and apply styles like color and font-family.

2. External CSS:

External styles are stored in separate .css files. Let’s create an external style sheet and link it to our HTML file.

styles.css:

h1 { 
color: blue; 
font-family: Arial, sans-serif; 
}

index.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>My First CSS Page</title> 
<link rel="stylesheet" href="styles.css"> </head> 
<body> 
<h1>Hello, CSS!</h1>
 </body> 
 </html>
  • The link element in the <head> section links to the external CSS file (styles.css).
  • The CSS rules are defined in styles.css and are applied to the HTML elements.

3. CSS Selectors:

CSS selectors are patterns used to select and style elements. Let’s explore some basic selectors.

Example:

/* Universal Selector */ 
* { 
margin: 0; 
padding: 0;
 } 
/* Element Selector */ 
h2 { 
font-size: 24px;
 } /* Class Selector */
  .text-red {
   color: red;
    } 
/* ID Selector */ 
#unique-element {
 background-color: lightgray; 
 }
  • The Universal Selector (*) sets margin and padding to zero for all elements.
  • Element Selector (h2) styles all <h2> elements.
  • Class Selector (.text-red) styles elements with class="text-red".
  • ID Selector (#unique-element) styles the element with id="unique-element".

4. CSS Comments:

Comments in CSS are essential for documenting your code.

/* This is a CSS comment. */
  • CSS comments are enclosed in /* ... */.

Leave a Reply

Your email address will not be published. Required fields are marked *