Fun game for practicing learning CSS: https://flukeout.github.io/
Using inline styles is a bad practice, for a couple of reasons:
- You’re cluttering up your HTML, and mixing content with styling.
- It’s hard to keep your code DRY if you use inline styling. If you wanted to add a second
div
with the same styling, you’d need to duplicate all that styling code.
Example of inline styles:
1<div style="width: 200px; height: 200px; background-color: red;">Here's my first div!</div>
Instead, use a stylesheet:
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Kicking it with some Divs</title>
6 <!-- This can also be put in a separate file -->
7 <style>
8 div {
9 width: 200px;
10 height: 200px;
11 background-color: red;
12 }
13 </style>
14 </head>
15 <body>
16 <div>Here's my first div!</div>
17 <div>Here's my second div!</div>
18 </body>
19</html>
Using an external stylesheet (separate file):
1<!-- index.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5 <head>
6 <meta charset="UTF-8">
7 <title>Kicking it with some Divs</title>
8 <link rel="stylesheet" type="text/css" href="style.css">
9 </head>
10 <body>
11 <div>Here's my first div!</div>
12 <div>Here's my second div!</div>
13 </body>
14</html>
1/* style.css */
2
3div {
4 width: 200px;
5 height: 200px;
6 background-color: red;
7}
8
9div {
10 width: 300px;
11 height: 100px;
12 background-color: blue;
13}
Which Style Rules Will Win Out?
The answer is that whichever rule comes latest in the stylesheet will take precedence (this is what the Cascading means). However, you can overwrite this default behavior by using a more specific selector.
Levels of specificity:
(From least specific to most specific):
- HTML Elements
- Class attribute
- id
- Inline styling
- !important tag
1/* This is an id */
2#green {
3 background-color: green;
4}
5/* This is a class attribute */
6.red {
7 width: 200px;
8 height: 200px;
9 background-color: red;
10}
11
12/* This is an HTML element*/
13div {
14 width: 300px;
15 height: 100px;
16 background-color: blue;
17}
18
19/* If multiple of the same style are defined, the one that comes latest in the stylesheet will win out */
20div {
21 width: 500px;
22 height: 100px;
23 background-color: red;
24}
id
s for an HTML element should be unique: no two elements should share the sameid
, and no element should have more than oneid
. Classes, however, don’t have these restrictions: an element can have multiple classes, and multiple elements can share the same class.