CSS (Cascading Style Sheets) is a stylesheet language that is used to change the presentation of an HTML or XML file. Using CSS will allow you to control the layout, colors, fonts, and animations of a web page.
Before you begin learning CSS, we recommend that you first learn the basics of HTML.
Why Is CSS Important
- CSS separates the content from design which makes it easier to maintain websites.
- CSS allows you to create responsive and aesthetically pleasing websites.
- CSS is cross-browser compatible, which will make your website look consistent across all browsers.
Basic CSS Structure
A CSS file consists of selectors with styles defined within them. The selector targets the HTML element or class, and the declaration block contains the declarations which alter the style of the elements/classes.
cssh1 { color: purple; font-size: 20px; text-align: center; }
In the above example:
h1
is the element being selected.- The declaration block, enclosed by curly brackets
{}
, consists of the styles for the element.- The declaration block contains properties
color
and valuespurple
.
- The declaration block contains properties
Including CSS In HTML
There are three different ways to include CSS in your HTML files: inline, internal, and external.
Inline CSS
Inline CSS is applied directly inside the HTML element. This method is not recommended because it’s harder to maintain and can cause naming issues in large projects.
html<h1 style="color: purple; text-align: center;">Hello, World!</h1>
Internal CSS
Internal CSS is placed within the <head>
section of the HTML document, enclosed by a <style>
tag. This method is often used when styling a single page.
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Introduction to CSS</title> <style> h1 { color: purple; text-align: center; } </style> </head> <body> <h1>Hello, World!</h1> </body> </html>
External CSS
External CSS is the most common method for applying CSS to an HTML file. To apply CSS to an HTML file externally, create a separate CSS .css
file, and link it inside the <head>
tag of the HTML file using a <link>
tag.
index.html:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Introduction to CSS</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Hello, World!</h1> </body> </html>
styles.css:
cssh1 { color: purple; text-align: center; }
Conclusion
In this guide, we went over the basics of CSS to get you started with designing and styling your HTML documents. We will go further in detail on CSS properties and best practices, as well as cheat sheets and syntax guides throughout this section.