External CSS
Exercise
- Create a new subfolder in the "CSS" folder and call it "css".
- In the subfolder, create a new file called "styles.css"
- Back in the "index.html" file, remove the inline css from the h1 tag and add a "link" to the "styles.css" file so that the code looks like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>CSS Intro</h1> <p>This is my first time using CSS</p> <p>CSS makes the website look good</p> <p>List of things I'm learning</p> <ul> <li>HTML</li> <li>CSS</li> </ul> <a href="https://www.google.com">Link to Google</a> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, add the following code:
h1 { color: blue; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
<link rel="stylesheet" href="./css/styles.css">
External CSS refers to a separate file that contains the styling information for a website or web application.
This
is linked to the HTML document via a <link>
tag in the <head>
section of
the
HTML page. The external CSS file usually has a .css file extension and contains all the CSS rules, styles, and
specifications for the website. This separation of style from the content of the HTML document allows for
greater
efficiency and ease of maintenance as the CSS code can be reused across multiple pages and updated in a single
location.
h1 { color: blue; }
An element selector in CSS is a specific HTML element that you want to target and style. It is a component of a
CSS
rule set which is used to determine what elements on a webpage should be styled and how they should be styled.
The
selector is usually defined in the left side of a CSS rule followed by the style declarations in curly braces on
the
right side. In this example, h1
is the selector and the style declaration within the curly braces
determine the color of all the <h1>
elements on the page. The semi-colon at the end of each
style
declaration is important. It is a syntax error to omit it, i.e. the code will not work properly.
Experiment with the Code
- Try making the header color red.
- Try changing the text color of the paragraphs.
- Try changing the text color of the list items.
Video and Code References
Questions? Subscribe and ask in the video comments: