# HTML integration
# CSS syntax
A set of CSS rules consists of a selector and a declaration block:
The selector points to the HTML element that you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and value, separated by a colon.
Multiple CSS declarations are separated by semicolons and the declaration blocks are surrounded by braces.
# Example
In this example, all <p>
elements will be center-aligned, with a red text color:
p {
color: red;
text-align: center;
}
# Example explained
- p is a selector in CSS (points to the HTML element you want to style:
<p>
). - color is a property and
red
is the property's value. - Text-align is a property and
center
is the value of the property.
# How to add CSS
When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.
There are three ways to insert a stylesheet:
- External CSS
- Internal CSS
- Inline css
# External CSS
With an external stylesheet, you can change the look of an entire website by changing just one file.
Each HTML page must include a reference to the external stylesheet file within the <link>
element, within the header section.
.
# Example
External styles are defined within the <link>
element, within the <head>
section of an HTML page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor and must be saved with a .css extension.
The external .css file must not contain HTML tags.
This is what the "mystyle.css" file looks like:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Note: Do not add a space between the property value and the unit.
👎margin-left: 20 px;
👍margin-left: 20px;
# Internal CSS
An internal style sheet can be used if a single HTML page has a unique style. Internal styles are defined within the <style>
element, within the <head>
section of an HTML page:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
# Inline CSS
An inline style can be used to apply a unique style to a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.
# Example
Inline styles are defined within the "style" attribute of the relevant element:
<!DOCTYPE html>
<html>
<body>
<h1 style="color:red;text-align:center;">This is a heading</h1>
<p style="color:blue;">This is a paragraph.</p>
</body>
</html>
Tip
An inline style loses many of the benefits of a style sheet (when mixing content with presentation). Use this method sparingly.