Where is CSS?
There are 3 places you can put CSS.
Inline CSS
Place your CSS within the content of an HTML page. Here's an example of inline CSS:
<p style="color: red;">hello world</p>
Which would create the following element:
hello world
Any HTML element can have a CSS style
inserted inside it. The style
is a kind of attribute, similar to the href
attribute in links.
Avoid Inline CSS
Inline CSS mixes the content and style of your web page, which makes it harder to maintain your code, so it should generally be avoided. However, sometimes it's convenient to quickly edit the appearance of an HTML element on the spot, and what's the worst that can happen?
(Inline CSS can also be useful when demonstrating CSS, so it will be used in some examples in this tutorial.)
External CSS file
Usually, you should use an external CSS file to add CSS to a web page. This keeps your content and styles separate, and makes it easy to share CSS between different pages. Here's how to use external CSS:
1 - Create a CSS file and save it with a .css extension, such as style1.css
.
2 - Add the CSS to your HTML web page with the following code inside the <head>
element:
<link rel="stylesheet" type="text/css" href="style1.css">
Make sure the file style1.css
is in the same folder as your web page. (Otherwise, you will need to adjust the path to it in the href attribute.)
Code Your Page
Can you add a external stylesheet to your HTML store from the HTML tutorial?
- Open up your simple HTML store from the HTML tutorial. (You can also download the HTML file here.)
- Copy the above code for including a CSS file to inside the
<head>
element in your page. - Create a new file
style1.css
in the same folder as your page. Add a simple style to it to test it out, such as the following:
p {color: gray;}
Now open your HTML page in the browser and all the paragraphs should be gray!
Internal style sheet
Internal style sheets place CSS on top of the HTML page, in a <style>
element inside the <head>
element. You saw an example in the previous page's challenge:
<html>
<head>
<style>
p { color: red;}
</style>
</head>
<body>
<p>Hello world</p>
</body>
</html>
This keeps the CSS mostly separate from the HTML, but it cannot be re-used between pages. Since it uses the same basic syntax as external CSS, we'll use it in these challenges so you can see the HTML and CSS all at once.
Challenge
Create a bold element (with <b>
tags) and put an inline style in it that sets the color to green. Then add the word goodbye
inside the element.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Add an internal stylesheet to the code below. Then add a style to it that sets the color of paragraphs (p
elements) to orange.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.