SITERAW

Setting up CSS

Hello and wel-

My website sucks! Everything is bland... I can't add color, center my text or even place an image where I want on my page. And don't even get me started on the gross blue and purple links. I wanted to create a website not some homo pride brochure for the Roma fashion week. Isn't that the purpose of this tutorial?

Right.

Don't worry, we'll fix that very soon.

We just finished the first part of this tutorial, about the HTML language, and we're about to begin the second part, about the CSS language.

As I explained during the first chapter, you need both HTML and CSS to create a fully functional and aesthetic website.

If you want an analogy, think of HTML as the bricks that allow you to build the walls of your house and CSS as the paint that lets you brighten it up.

Until now we've only worked with HTML so your house looks like... bricks.

This is the first chapter of the second part of this tutorial and it will therefore deal with the fundamentals aspects of the CSS language.

I'm sure you have more than a few interrogations.

  • What is CSS?
  • Why was CSS invented?
  • What does CSS look like?
  • Where do you write CSS code?
  • Why is the author so awesome?
  • Is CSS complicated?

Rest assured, we will cover everything you can imagine and more in this first chapter.

Introduction to CSS

Having spent the first part of this course learning about HTML, we're about to dive into the CSS language that we intentionally sidelined until now.

CSS is no more complicated than HTML. It's simply a distinct language that serves a different purpose.

The CSS acronym stands for Cascading Style Sheets and as you may have guessed from the name it's used to format and stylize your website.

In HTML we learned how to tell the browser:

  • I want a title here.
  • I want a paragraph here.
  • I want a list here.
  • I want an image right after that.

With CSS we'll learn how to say:

  • I want my titles to be in italic.
  • I want my paragraphs in red.
  • I want my lists to use a different font.
  • I want my image centered.

Here is an actual example of CSS in action.

CSS in action

This demonstration will show exactly how the inclusion of the CSS language can transform a website.

Take the following HTML web page.

It's very basic and contains most of the elements we've already covered in this tutorial.

Pure HTML page, no CSS
Pure HTML page, no CSS

This is our rudimentary HTML page (the one you were complaining about).

Yours shouldn't look much different.

Without modifying any portion of the HTML code, let's simply add some CSS to make it easier on the eye.

Here I added some very basic CSS.

A web page with basic CSS
A web page with basic CSS

It's already better.

But that example is just applying the fundamentals of the CSS language.

If you want to see the full potential of CSS, here's a demonstration of some advanced properties.

Advanced CSS in action
Advanced CSS in action

All three examples come from the exact same HTML page.

The content (HTML code) is identical but the format (CSS code) is what makes these pages look different.

Cool! My website can finally get untarded! But how do I use CSS?

Keep reading to find out.

Writing CSS code

There are three ways you can apply CSS code to a web page or a portion thereof.

You can write CSS code:

  • in a separate .css file (recommended)
  • in the <head> tag of your page
  • in the HTML tag directly by way of the style attribute

The first method is the most commonly used and you'll understand why once we've presented all three techniques.

Writing CSS in a separate file

This is the standard method of CSS inclusion and the one I recommend.

The purpose is to place the CSS code in a .css file which will be included in one or more .html web pages.

Including a CSS file in a web page is extremely easy: all you need is one HTML tag which will go in the <head> portion of your document.

Have a look at the HTML code below.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>SiteRaw</title>
        <link rel="stylesheet" href="style.css" /> <!-- A new tag appears -->
    </head>

    <body>
        <h1>Welcome to SiteRaw</h1>

        <p>SiteRaw is the best site on the web!</p>

        <p>Why is SiteRaw so <em>awesome</em>? I don't even know.</p>
    </body>
</html>

This code looks more or less like every other HTML web page we've encountered up until now, except for the new tag in the header (on the fifth line).

This is the line I added.

<link rel="stylesheet" href="style.css" />

As you can see, this HTML tag has two attributes.

The <link> element indicates a relationship between the current document and an external resource.

In our case the resource in question is a CSS style sheet, but it could also be an RSS feed (XML), a favicon, an iPhone or tablet icon, an internal search engine and so on.

These are the two attributes present on the <link> tag.

  • rel specifies the relationship between the linked document (the CSS file) and the current document (the HTML web page). It stands for "relationship". In our case, the linked file is a style sheet so its value is stylesheet. Simple.
  • href stipulates the URL of the linked resource. We already mentioned this attribute when we introduced text links in the first part of this tutorial. In our case, the value is relative path to the CSS file we want to include: style.css.

Now we know how to include a separate CSS file in our web page.

But I don't have a CSS file to include in my web page! I only have a .html web page.

That's because we haven't created our CSS file yet.

Don't worry, we'll get to that in a moment.

Speaking of which, how do you edit CSS code? Do you need specific software?

Good question.

CSS code is created and edited in the same manner as HTML code. All you need is a text editor (Brackets, Visual Studio, Sublime, Notepad...).

Now let's create our first CSS document.

Open your text editor and create a new file. With Brackets simply go to File > New.

Your document should be empty for now, that's not a problem.

Save your file with a .css extension.

In our example the file is called style.css but you can give it the name you want.

What's important is that you save your new CSS file in the same directory your current HTML web page.

Your folder should look like this.

Your HTML and CSS files
Your HTML and CSS files

I recommend you use the same names as me for your HTML and CSS files.

If you choose not to, make sure that the files names and the value of the href attribute match.

Here is what you should see in your text editor.

HTML and CSS text editor
HTML and CSS text editor

Both files are currently opened in the text editor.

All that's left is to see if the style sheet is properly applied to our web page.

Double click on the icon of the .html file to open it in your browser.

You should get the following.

Your web page in a browser
Your web page in a browser
This sucks! It looks exactly the same as everything we've done until now!

That's because we haven't added or included any CSS yet. Remember, our CSS file is empty.

Let's remedy that.

Open your CSS document and add the following code.

p
{
    color: blue;
}

Don't worry about what this code means for the moment.

Reload the web page in your browser and witness the magic of CSS.

Your paragraphs are now displayed in blue.

The paragraphs are blue
The paragraphs are blue
CSS files are not intended to be loaded directly in the browser. If you open your .css document with a web browser it will simply show your code as text. Only HTML files are interpreted by the render engine.

That is the recommended method of CSS code inclusion.

Now let's see the two others in action.

Writing CSS in the header

The second way of applying CSS is by writing your code inside a <style> tag within the <head> element.

The following code produces exactly the same result as the demonstration above.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>SiteRaw</title>
        <style>
        	p
		{
		    color: blue;
		}
        </style>
    </head>

    <body>
        <h1>Welcome to SiteRaw</h1>

        <p>SiteRaw is the best site on the web!</p>

        <p>Why is SiteRaw so <em>awesome</em>? I don't even know.</p>
    </body>
</html>

Test it and see for yourself, you should get the exact same result.

Writing CSS directly in a tag

The last method is the least recommended.

Use it only for testing purposes or if you have no other alternative.

You can use the style attribute on the specific tag you want to format. This is a global attribute, meaning it works on any HTML element.

Just write the CSS code you want to apply as the value of the style attribute.

This example contains only the code inside the <body> element.

<h1>Welcome to SiteRaw</h1>

<p style="color: blue;">SiteRaw is the best site on the web!</p>

<p>Why is SiteRaw so <em>awesome</em>? I don't even know.</p>

In this case, since the CSS was applied to the first <p> element alone, only the topmost paragraph will be blue.

The best method of CSS code inclusion

I don't understand why you recommend using the first method. Why do I need to create a new file for CSS? I was doing fine with just a .html page.

For now it may seem that separating the HTML and CSS code in two distinct files is unnecessary and only serves to makes things more complicated.

In reality, far from complicating the process it's actually the most convenient solution.

Most websites are comprised of several pages that share a common CSS theme.

If you were to mix HTML and CSS code in the same document, you would have to copy your CSS style from one page to another and on every page of your website.

And editing it would prove nearly impossible... you would have to manually modify every page.

Whereas with a separate .css file, all you have to do is edit the code once to modify the design of your entire website.

That's why this method is the most used and the one I recommend.

Applying a CSS style

Now we know where to write CSS code. Great.

But that's not going to be very useful unless we know how to write code in the CSS language.

A bit earlier I gave you an example of CSS code without explaining it any further.

p
{
    color: blue;
}

You probably guessed its function: this code displays every paragraph in blue.

CSS code contains three essential elements:

  • the selector: in our case we want to format the content between the <p> tags, so our selector is p. Tag names (<p>, <h1>, <strong>...) are very common selectors in CSS. Just remember to remove the angle brackets.
  • the CSS property: the formatting effect that you want to modify. In our case it's the color of the text, so the CSS property we use is color.
  • the property value: the value of the aforementioned CSS property. For every property you must specify a value. In our example we used the color property, so we must specify a color. In our case it was blue.

For each selector you can insert any number of properties you want.

The syntax is CSS is easy to remember.

  • You enter the selector, for example a tag name without the angle brackets.
  • You add braces: { and }.
  • Within these braces, you can modify as many properties as you want.
  • Each property starts with the property name, then a colon :, then the associated property value and finally a semi-colon ; to mark the end of the line.

Our CSS code therefore means "I want all my paragraphs to be written in blue".

CSS code syntax
CSS code syntax

But if we change any of three elements, either the selector, the property or the value, the display effect will vary accordingly.

Let's try changing the selector.

h1
{
    color: blue;
}

Open your HTML page again and you should see the title written in blue this time.

HTML page with a blue title
HTML page with a blue title

We can also change the value of the color property.

Let's make our paragraphs red.

p
{
    color: red;
}

And the result.

HTML page with red text
HTML page with red text

CSS is like magic. Almost.

Comments in CSS

As with HTML, you can include comments directly in your CSS file.

Neither HTML and CSS comments are displayed or interpreted by the web browser.

They are just notes and instructions about your web page or style sheet that only you can see.

CSS comments are contained between two markers: /* indicates the beginning of a comment and */ indicates its end.

Comments in CSS can be placed on one or several lines, as shown in the example below.

/*

This is my CSS style sheet.

It turns every paragraph red!

*/

p
{
    color: red; /* Paragraphs will be red. */
}

CSS comments aren't used very often but you should know how they work in case you ever need to document your code.

Advanced CSS selectors

Let's talk a bit about selectors.

In this chapter, we learned how to use CSS to tell the browser:

  • I want my titles <h1> written in blue.
  • I want my paragraphs <p> written in red.

But what about other commands?

What if we want to say:

  • I want my titles <h1> and my paragraphs <p> written in pink.
  • I want only the first paragraph <p> written in blue.
  • I want every emphasis <em> within a title <h1> written in red.
  • I want every paragraph <p> that directly follows a title <h1> written in green.

Those are some inappropriately specific directions.

But can CSS execute them?

Of course it can.

Applying a style to multiple tags

Imagine that we want both our title <h1> and our emphasized text <em> to be pink.

You could very well use the following code.

h1
{
    color: deeppink;
}


em
{
    color: deeppink;
}

Don't worry about deeppink, it's just a different shade of pink.

Try it out and see if everything works.

It works... but isn't it kind of repetitive to write every tag you need to format? What if I want three or four tags to be blue, do I need to write the same code three or four times?

As it turns out you don't need to repeat any portion of your code.

In the same way you can add multiple CSS properties to a single HTML tag (for example color and font-size), you can also use multiple HTML tags as the CSS selector.

To combine two CSS selectors just separate them by a coma.

h1, em { color: deeppink; }

This code produces the exact same results as the longer version shown higher above.

You may have noticed that I shortened the CSS code slightly on my last demonstration. Specifically, I wrote every element (selector, property and value) on the same line. It's entirely optional. For this tutorial, I'll continue to use the longer code structure as it is more readable.

Here is what this should give you.

Pink title and emphasis
Pink title and emphasis

You can format as many tags one after the other as you want.

The class and id attributes

Everything we've seen so far still falls short on one aspect.

If you tell the browser to render your paragraphs in blue, than every occurrence of the <p> element will be displayed in blue.

What if you want separate paragraphs to be formatted differently? What if you only want the first paragraph to be pink?

That's a good question.

You could always use the style attribute to apply CSS only to the specified tag but we've already advised against this method.

Fortunately there is a simple way to solve this problem.

We can use one of two attributes:

  • the class attribute
  • the id attribute

These are called global attributes as they work on every HTML element (style is also a global attribute).

Perhaps you remember the id attribute from chapter on links when we used it to create anchors.

You gave it whichever value you wanted and that value served as an identifier for the HTML tag. The only requirement was that no two tags could share the same id.

The class attribute works in a similar fashion.

The difference is that you can have as many elements share a class as you want.

Here is the example of a paragraph belonging to the "siteraw" class.

<p class="siteraw">SiteRaw is the best site on the web!</p>

Since we are using a class attribute we can apply it to several HTML elements.

<h1>Welcome to SiteRaw</h1>

<p class="siteraw">SiteRaw is the best site on the web!</p>

<p>Why is SiteRaw so <em class="siteraw">awesome</em>? I don't even know.</p>

Both the first paragraph (<p>) and the emphasis (<em>) belong to the class siteraw.

We can use this attribute in CSS to say: I only want the tags marked "siteraw" to be written in orange.

To select a class attribute in CSS, simply enter its name preceded by a dot . as the selector.

.siteraw
{
    color: orangered;
}

Test the result.

Only your first paragraph and the emphasis will have a different color.

First paragraph and emphasis in orange
First paragraph and emphasis in orange

The id attribute is used in the exact same way as class.

The only difference is that it is prefixed by a hash character (#) rather than a dot (.) in the CSS style sheet.

Here is an HTML demonstration code.

<h1 id="siteraw">Welcome to SiteRaw</h1>

And the associated CSS.

#siteraw
{
    color: blue;
}

Other than that, id works exactly in the same way as the class attribute.

General purpose tags

Let's say you want to apply a specific format to some words that were not originally surrounded by tags.

For instance, let's have a look at the first paragraph in our demo.

<p>SiteRaw is the best site on the web!</p>

What if we want to have the text "SiteRaw" displayed in red?

The problem with class and id is that they are attributes and as such must be used on an specific HTML tag. But there is no tag that surrounds the word "SiteRaw" alone.

We could always insert a <em> or <strong> tag, add some color and remove the inherent text effects (italic or bold respectively).

But remember the rule of web development? HTML is for content, CSS is for style.

To add a <em> or <strong> element would imply that the text contained in these tags requires emphasis.

What is we just need to format it without emphasizing it?

Luckily, there are two tags in the HTML language that permit exactly that: they are called general purpose tags.

These tags share the particularity that they don't communicate any semantic information to the user agent.

But that doesn't mean that they are useless, quite the contrary.

You can think of them as placeholder elements and are used mostly for CSS formatting.

These are the two general purpose tags that exist in HTML.

  • <span> is an inline element like <em> and <strong>. Inline elements take only as much width as required and don't start on a new line. They are usually employed within a block element. This is the tag we'll use for our example.
  • <div> is a block element like <p> and <h1>. It stands for "division". Block-level tags occupy the entire horizontal space of their parent container thereby forcing a new line break before and after the element.

We've already mentioned the block and inline dichotomy so you're probably familiar with it by now.

For our example, we only want the text "SiteRaw" to be affected by CSS so we will use the <span> tag.

<p><span class="siteraw">SiteRaw</span> is the best site on the web!</p>

And the CSS code.

.siteraw
{
    color: red;
}

This should give you the following result.

SiteRaw is the best site on the web!

Since we are only applying a style to a single tag we could use either class or id for this purpose, it would make no difference.

If we needed to select two separate portions of text however, we would have to use class.

More advanced selectors

You now know how to apply a CSS style to either a single tag, multiple tags or specific tags marked by either the class or id attributes.

Here are some other ways to target specific portion of your content using CSS.

The universal selector

What if you want to target every tag in your HTML document?

Simply use the universal selector *.

* { color: red; }

This selector isn't used very often as most HTML tags inherit CSS properties from their parent elements.

You might have noticed that when we turned our paragraphs blue, the <em> tag contained within a paragraph was also displayed in blue.

We didn't need to stipulate that we wanted both <p> and <em> elements to be blue because <em> inherited the color property from its parent element (<p>).

As you, if you wanted to make every occurrence of text on your web page to be red, you would modify the color property on either the <body> or the <html> tags rather than use the universal selector.

This selector still has its occasional uses and you should at least know it exists in case you ever need it.

A tag within another

Take this HTML code.

<h3>Welcome to <em>SiteRaw</em>!</h3>

What if we want to select the <em> inside the <h3> element?

Technically we could add a class or id attribute to the emphasis and apply our style to that instead, but isn't there an easier way?

Let's find out.

h3 em { color: red; }

This code selects every <em> tag inside an <h3> element.

The syntax is A B, not to be confused with A, B which selects both the A and B elements regardless of their containers.

This is called a descendant selector or child selector.

Direct child selector

Sometimes the descendant selector goes a bit overboard and formats more than we want.

The reason is that it selects every occurrence of tag A contained in HTML element B.

To understand a bit better, look at the following code.

<p>
    <span>Why is <span>SiteRaw</span> so awesome?</span>
</p>

Let's try to format our code using the selector we just learned about.

span { color: blue; }
p span { color: red; }

This tells the browser: I want every <span> to be blue but every <span> within a <p> to be red.

The second style overrides the first and indeed, our text is now red.

Why is SiteRaw so awesome?

Everything works.

But wait... Why is the text "SiteRaw" red? Shouldn't it be blue since it's not contained within a <p>?

That's not exactly true.

The "SiteRaw" text is contained within a <span>, which is itself inside a <span>... inside a <p>.

The nesting hierarchy is as follows: p > span > span.

So technically, it is contained within a <p> which is why the text is red.

But I see your point.

What if we want to only select the tags that are direct children of a parent element?

In our example that would mean only formatting those whose hierarchy is p > span and leaving out the "SiteRaw" text.

For that we have the direct child selector.

Let's update our CSS code.

span { color: blue; }
p > span { color: red; }

Now you should see.

Why is SiteRaw so awesome?

The "SiteRaw" text is not affected by the second line of our CSS so its formatting reverts to the original rule (first line) that applies to all <span> tags: blue text.

The syntax of a direct child selector is A > B.

It selects every instance of a B element of which the direct parent is an A tag.

A tag after another

Let's go back to our demo page.

<h1>Welcome to SiteRaw</h1>

<p>SiteRaw is the best site on the web!</p>

<p>Why is SiteRaw so <em>awesome</em>? I don't even know.</p>

Throughout this chapter, we saw how we could format the the paragraph only by assigning it a class or id attribute.

But is that the only way?

What if we want to select every paragraph that immediately follows an <h1> title?

Try this out.

h1 + p { color: red; }

This code selects the first <p> tag located after an <h1> title.

The syntax is A + B so don't confuse it with what we just learned above.

This is called the adjacent sibling selector.

General sibling selector

Let's see the HTML code first and the explanations second.

<p>Blue</p>

<div>
    <p>Blue</p>

    <h3>Welcome to SiteRaw</h3>

    <p>RED</p> <!-- This tag -->

    <div>
        <p>Blue</p>
    </div>

    <div>
        <h3>Guess the color</h3>
        <p>RED</p> <!-- This tag -->
    </div>

    <p>RED</p> <!-- And this tag -->
</div>

<p>Blue</p>

This code seems pretty self explanatory.

You have to format every tag that says "RED" without modifying the HTML code.

And before you ask, there is no selector that allows you to mark an element based on the text it contains.

The answer only takes one line of CSS code.

h3 ~ p { color: red; }

We should also make the default text blue but I trust you know how to do that by now.

So what is this new selector?

It's called the general sibling selector and combines a few properties from the selectors we've learned about previously.

The A ~ B selector marks all instances of B elements that follow and share the same parent as an A tag.

In our example it means that the <p> tag must:

  • share the same parent as a <h3> tag
  • come after a <h3> title (though not necessarily directly after)

Try it out.

The three tags that say "RED" will be displayed in red. Success.

A tag with an attribute

Can CSS select a tag that holds a specific attributes?

Let's find out.

a[title] { color: red; }

This will affect every <a> tag that has a title attribute regardless of its value.

What if you want to specify a value?

a[title="SiteRaw"] { color: red; }

This will only affect <a> elements whose title attribute has the value SiteRaw.

It will not format:

  • tags other than <a> (regardless of attributes)
  • tags with no title attribute
  • tags whose title attribute's value isn't SiteRaw

And finally, what if you want it to contain the value SiteRaw rather than check for exact match?

a[title*="SiteRaw"] { color: red; }

The only change is the addition of an asterisk *.

Combo selectors

Lastly, know that you can combine multiple CSS selectors into one mega-selector.

For example you can merge the type selector with the class selector.

p.siteraw { color: orangered; }
em#siteraw { color: orangered; }

This code will format every <p> element of the "siteraw" class and every <em> element of the "siteraw" id.

Here is a demonstration.

<p id="siteraw">Welcome to <em id="siteraw">SiteRaw</em>.</p>

<p>Welcome to <em class="siteraw">SiteRaw</em>.</p>

<p class="siteraw">Welcome to <em>SiteRaw</em>.</p>

Try it out.

Only the first emphasis and last paragraph should be orange.

Welcome to SiteRaw.

Welcome to SiteRaw.

Welcome to SiteRaw.

When we write .siteraw or #siteraw alone as the selector, what we're implying is that we want *.siteraw or *#siteraw meaning any tag that possesses that class or id. Both methods produce the same result. The shorter form is generally preferred so it's the one we'll be using in this tutorial.

Summary

There are a few more cases we haven't covered, not least of which what we call pseudo-classes.

They almost deserve a chapter of their own. We'll get to them soon enough.

You don't have to remember every single selector of the CSS language.

Most of the examples presented in this chapter are of situational use only. I can't remember the last time, if there even was one, where I needed to format links that contained a title attribute differently from the rest of the links.

The three main selectors you should remember are as follows.

ExampleSelectorExplanation
h1Type SelectorSelects an element by its tag name (type).
.classClass SelectorSelects an element by its class attribute value.
#idID SelectorSelects an element by its id attribute value.

These are the principal CSS selectors we will be using in this tutorial.