How to use CSS codes
There are 3 ways to use CSS in your html site. We will tell you these ways. Let's start the lesson of using css with how it is used and how to add code.
When a web page is viewed from a browser, the codes are interpreted from top to bottom. And it shows the codes it interprets to the end user on the page. That's why CSS codes should always be written in the <head> tag. Because it will interpret the headers inside the <head> tag before displaying the content, and if it sees a CSS file being called, it will load it before displaying the content and show the contents with the style applied.
1- Ways to Add CSS Codes
There are 3 different ways to use css in HTML. These;
- External style sheet
- Built-in style tag
- Inline style attribute
Now let's examine what these are in turn.
Using CSS codes in an External Style File
A CSS file is included in the page using the <link> tag within the <head> tag. The file extension of CSS files is .css. For example, if we want to include the style.css file on the page;
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
The important thing in these codes is the href attribute, here we determine the path of the css file.
2- Using CSS' codes with Style Tags
Instead of a css file, we can define CSS codes directly within our HTML page. I don't recommend this highly, but let's see how it's done anyway. You don't have to define it in the <head> tag, you can define it in the body.
<body>
...
<style>
body {
background-color: #eee;
}
</style>
...
</body>
3- Using CSS with the style attribute
If you want to apply CSS directly to a tag within the HTML page, you can use the style attribute. For example;
<p style="background-color: yellow"> paragraph </p>
Using !important in CSS
The browser displays whatever the last style value is in the css codes you add. But as an exception, if !important is used it will apply it. For example, if we put !important at the end of the value we wrote in the <style> tag;
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
h1 { color: green !important; }
</style>
</head>
We told the browser that this is more important and it will no longer consider it, even if there is another style definition at the bottom. Of course, if there is an important in the style definition at the bottom, then it will take the last one into account in the same order.