-
Notifications
You must be signed in to change notification settings - Fork 0
Week 3_1(en): Adding CSS to HTML
We learned in our first class that CSS is used for styling purposes as opposed to HTML, which defines the structure of our web page. Let's learn how to use CSS to add style to our page!
Before starting, let's make a directory in your computer (or in your USB if you have one) named date-your name
.
Then click the below files to copy them.
Make sure you save them in the directory you have just created.
index.html
about.html
memo.html
seoul image
Create a directory named img
in your date-your name
directory and move seoul.jpg
into img
. (Ctrl + X, Ctrl + V)
Try adding the following attribute in the first h1
tag in index.html
.
style="color: red;"
Inline styles are a quick way of directly styling an HTML element.
If you want to add more than one style with inline styles, simply keep adding to the style attribute.
style="color: red; font-size: 20px;"
HTML allows you to write CSS code in its own dedicated section with the <style>
element.
Try adding the following code inside the <head>
element in index.html
.
<style>
h1 {
color: red;
font-size: 20px;
}
</style>
On the browser, you will notice that your style has been applied.
This is a useful way to apply and maintain styles to multiple elements at once.
Unlike inline styling, you can specify which elements to apply the styling to.
However, as our CSS code gets more complex, it is better to make a separate CSS file.
Let's make a directory named stylesheets
in your directory and create a text file named blog.css
.
Now let's erase the <style>
element and type in the following code instead.
<link rel="stylesheet" href="stylesheets/blog.css" type="text/css">
The <link>
element is an empty element with the following attributes:
-
href
: the value of this attribute must be the path to the CSS file. -
type
: this attribute describes the type of the document you are linking to. -
rel
: this attribute describes the relationship between the HTML file and the CSS file.
By using this <link>
tag, we can import the code inside blog.css
and apply it to our index.html
page.
You can add the same code to both about.html
and memo.html
.
In the blog.css
file, write the CSS code we had written inside the <style>
element and check the browser again.
It is a good practice to make a separate .css
file because
- we can avoid mixing HTML and CSS code
- we can write all the CSS code needed to style a page without sacrificing the readability and maintainability of our HTML file
- we can add style to multiple pages in a flexible way
Note that a.css
file is a pure CSS file, so we do not use any HTML code inside the file.