Categories
Web development

CSS Basics

CSS (Cascading Style Sheets) like HTML is not a programing language. It is a style sheet language. CSS is used to define styles for websites, including the design, layout, and variations in display for different devices and screen sizes.

CSS Basics

The CSS Syntax consists of a set of rules. These rules have 3 parts: a selector, a property, and a value

Syntax: 

CSS Syntax

This code tells the browser to render all occurrences of the HTML <h1> element in green with the font-size 14px. 

Example:

<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: green;
  text-align: center;
}
</style>
</head>
<body>

<p>Good afternoon!</p>
<p>These paragraphs are green and styled with CSS.</p>

</body>
</html>

Output:

Good afternoon!

These paragraphs are green and styled with CSS.

A CSS Comment is used to add explanatory notes to the code. Comments are ignored by browsers. Comments can be placed whenever white space is allowed within a style sheet.
A CSS comment starts with /* and ends with */. Comments can also span multiple lines. 

Example:

<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: green;
  /* This is a single-line comment */
  text-align: center;
}

/* This is
a multi-line
comment */
</style>
</head>
<body>

<p>Good afternoon!</p>
<p>This paragraph is green and styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>

</body>
</html>

Output:

Good afternoon!

This paragraph is green and styled with CSS.

CSS comments are not shown in the output.

The CSS element selector selects HTML elements bases on element name. It will be better to group the selectors, to minimize the code. To group selectors, separate each selector with the comma.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
  text-align: center;
  color: green;
}
</style>
</head>
<body>

<h1>Good afternoon!</h1>
<h2>Smaller heading!</h2>
<p>Paragraph.</p>

</body>
</html>

Output:

Good afternoon!

Smaller heading!

Paragraph.


Enjoy coding!

Read also:

CSS Selectors

CSS Reference