-
Notifications
You must be signed in to change notification settings - Fork 116
12. Where to Create Rules
Styles can be added to a document in a number of ways — inline styles, document level styles or as external stylesheets. We have now seen inline and document level styles using <style>
.
Inline styles that use the style
attribute are usually too specific and are difficult to maintain.
The document level styles that we have in <style>
work well but they only apply to index.html
. To use the same styling rules on all four of our HTML files we need to use an external stylesheet.
Currently, our rules are inside the <style>
tag and only apply to index.html
.
So that we can have a consistent style across our four files we’ll move to an external stylesheet.
To do so, copy the rules you have created into a new stylesheet file, saved with a CSS extension. For this purpose, there is an empty file set up for you in the styles
folder called main.css
.
Remove the rules from the <style>
tag in the <head>
of index.html
.
Move all the rules to the main.css
stylesheet.
Then, in the <head>
, add the <link>
to attach this external stylesheet.
Your HTML should appear as follows:
<link href="styles/main.css" rel="stylesheet" type="text/css">
Try attaching this stylesheet to the other files in the sequence with the <link>
tag. Again place the <link>
in the <head>
of the documents.
An alternative way to attach a stylesheet with <style>
and @import
.
Note
@import
is an example of an 'at-rule' in CSS that inform the CSS how to behave.
Here we place the @import
inside of the <style>
in the <head>
.
<style>
@import url(styles/main.css);
</style>
As the @import
is CSS syntax it can be placed inside a <style>
or an external CSS file. This means that this technique can be used to import one stylesheet into another.