Lesson 4: CSS

Now to the fun part: CSS.

CSS is used to style your HTML elements. You adjust colors, backgrounds, and layouts of different tags to make them look however you want.

CSS can be written directly into the same HTML file by adding a style tag inside the head element:

<!DOCTYPE html>
<html>
<head>

<style>
/* CSS styles added here */

</style>
</head>

<body></body>
</html>

The /* */ is used to define a comment in CSS. Comments are used to provide helpful annotations to help other people understand your code.

Another way we can include CSS into our website is by linking a CSS file inside the head tag. To link a CSS file, we use the link tag, with the rel & href attributes. For example:

<head>
	<link rel="stylesheet" href="/styles.css">
</head>

link tags, as shown above, are also self-closing tags. The rel attribute specifies the relationship of the link to the HTML document, and in this case, the CSS file is the stylesheet. The href attribute specifies the URL of the CSS file.

Styling Elements

CSS is made up for selectors, properties, and property values. For example, lets create an h1 tag, with the value “Hello”, and style it to make the color of the text red.

<!DOCTYPE html>
<html>
<head>

<style>
	h1 {
		color:red;
	}

</style>
</head>
<body>

	<h1>Hello</h1>

</body>
</html>

To style an element in CSS, we must first define a selector. A selector defines (or selects) the tag we want to style. In this example, h1 is the selector, meaning that we selected all h1 tags in the HTML documents to style. The selector is followed by curly braces, in which the properties that we’re using to style the elements are in. color is a CSS property used to change the color of text in a HTML element. A property is followed by a colon, the property value, and then a semi-colon. We can define as many properties as we want on a given element. Try changing the color of the HTML element to “blue”, “yellow”, or even “green”.

There are many different CSS properties, and we’ll cover a lot of them in the following lessons. One more cool CSS property is font-size, which is used to adjust the size text of an HTML element. Let’s adjust the h1 tag above to be a little big bigger.

<!DOCTYPE html>
<html>
<head>

<style>
	h1 {
		color:red;
		font-size: 90px;
	}

</style>
</head>
<body>

	<h1>Hello</h1>

</body>
</html>

px is a unit of measurement in CSS, and it stands for pixels. Your phone/laptop/iPad screen is made up of a lot of pixels, and this unit defines how many pixels the element should take. In the above example, the h1 element will cover 90 pixels.

I encourage you to play around with these properties, and style them differently by using the editor on the right. Include an h2 element with your name, and change its color to be pink. Style the font-size however you want. When you get a bit familiar with CSS selectors and properties, move on to the next lesson.