CSS: Foundation — Get Started

CSS Get Started

Learning outcomes:

  • The style attribute
  • The <style> element
  • External style sheets
  • Which approach to use

Now that we know what CSS is, we can move on to discover where can it be actually written. There are a couple of places where CSS code can go, each having its own unique use.

In this very chapter, we'll go through all of these places and understand each one's purpose and use case.

Let's go!

The browser environment

Akin to HTML, CSS doesn't require you to install anything special on your computer to get it into action. All you need is a web browser, which you definitely already have (unless you're using an ancient computer).

This is perhaps one of the best parts about learning HTML and CSS — we don't have to worry about installing anything in order to get started.

For many computer languages, the environment setup is not a trivial thing to do, and sends shivers down many beginners. Fortunately, this isn't the case with CSS.

Sure, we might install a coding editor, such as Visual Studio Code (a very popular choice these days) in order to help us out while writing CSS, the main point is that it isn't required.

Where to write CSS?

On the web, CSS itself doesn't hold much value. In fact, I'd even go as far as saying that it holds no value until and unless it's paired with an HTML page and used to style some aspect of it.

In other words, CSS code has to be integrated with an HTML document in order for it to be useful; otherwise, it's just some chunk of styling information with no significance.

Speaking of which, there are 3 different places where CSS can be placed in order for it to be used to beautify some HTML:

  • The HTML style attribute
  • The HTML <style> element
  • An external style sheet

If you've been following through the HTML course on Codeguage, you'll already be aware of all three of these, and how to use them, on the outskirts.

We cover CSS in the following chapter from our HTML course: HTML Metadata — Style Sheets.

But even if you didn't, no need to worry, for we'll explore them in detail in this chapter.

The style attribute

Do you recall the purpose of the attribute of an HTML element? Well, an HTML element's attribute defines a particular characteristic of that element.

For instance, the href attribute of an <a> element defines the URI where the underlying (source) anchor element points to. Similarly, the cite attribute of <blockquote> defines the source of the quote (if available).

On the exact same lines, all visible HTML elements have an attribute called style.

As per its name,

The style attribute is used to define the styles of a given HTML element.

Since these styles are right there in the HTML markup, right inside the element's tag, they're often referred to as inline styles.

The value of the style attribute is CSS code.

Let's consider a simple example of styling an HTML element using some barebones CSS (we'll explore the precise syntax of this CSS code in the coming chapter, CSS Syntax).

Following we have a <p> element with some text in it:

HTML
<p>This is a paragraph</p>

This is a paragraph

We want to color the text red (perhaps to indicate that it represents an error message). In order to achieve this, we can set the style attribute on the element as shown below:

HTML
<p style="color: red">This is a paragraph</p>

Here's the magic this one-liner CSS brings:

This is a paragraph

Amazing, isn't it?

A superpower!

When I was learning CSS years back, I felt as if some superpower was being given to me. No really!

Being able to create documents using HTML did feel amazing as well but CSS hit differently. I don't know if you feel the same way right now (given that you're a complete beginner) but that's what I felt. If you feel the same, do let me know on Discord.

With CSS, you get this almost infinite world of possibilities to style HTML in millions of different ways. You become kind of like a designer (although, there's a lot lot more that one needs to learn to be called a designer actually).

To quickly explain the CSS code above (and we'll dive into this in more detail in CSS Syntax), color is a style property. It defines one aspect of the underlying element's style — in this case, it's (text) color.

Some other aspects could be the borders of the element, its inner spacing, its background color, its width, height, typeface, and whatnot. All these aspects, in addition to tons and tons of others, are governed by different CSS properties.

red is the value of the color property. In this case, it's a keyword that represents a color value in CSS.

More specifically, red is a value of the color type. We'll learn more about types of values in CSS in the chapter CSS Data Types.

The <style> element

Apart from the style attribute, which directly targets a given element, CSS can also be generalized to an HTML document and be put inside a <style> element.

The <style> HTML element defines a CSS style sheet for the underlying HTML document.

A style sheet is basically just a block of CSS code generalized to a document.

Inline styles don't represent a CSS style sheet because they directly target a particular element, NOT different aspects of an HTML document in general.

As you can guess, <style> is a container HTML element; CSS code goes inside the element (i.e. between the starting <style> and ending </style> tags).

Let's consider an example to help understand the way to lay out CSS code inside <style>.

Below we have the same paragraph as shown above:

HTML
<p>This is a paragraph</p>

This is a paragraph

And again, as before, let's try to color this paragraph red.

Here's the <style> element right above the paragraph:

HTML
<style> p { color: red; } </style>
<p>This is a paragraph</p>

Let's first see the output and then quickly understand what's happening here:

This is a paragraph

Perfect!

So what's happening in the <style> element here is that we have a style definition for all <p> elements.

The p right at the start defines what's called a selector. It specifies an expression to be used to match given HTML elements in a document and then apply the following CSS styles to all those elements.

And this takes us to the notion of a style declaration block — the entire chunk of code from { to }, following a selector. The declaration block holds the entire set of CSS styles to be applied to all the elements matched by the given selector.

You'll very shortly see why a style declaration block is called a 'declaration' block.

In this case, the selector p selects all <p> elements and then colors them red.

Notice the same color: red expression here that we saw previously in the style attribute; it's the same because inside both, the style attribute and a style definition in a CSS style sheet, we have a set of CSS style declarations (hence the name, 'style declaration block').

A style declaration is just a fancy name for a property-value pair.

Now, because the CSS code laid out above applies to all<p> elements in the HTML document, it makes us curious to add another <p> element and verify it rightaway.

Let's do this now:

HTML
<style>
   p { color: red; }
</style>

<p>This is a paragraph</p>
<p>This is another paragraph</p>

And now it's time for the big moment (drumroll...):

This is a paragraph

This is another paragraph

Live Example

Wow! Both the paragraphs are colored red, all thanks to the <style> element and the p selector (for applying given styles to all <p> elements).

You could sprinkle in as many <p> elements as you want to in this simple HTML code and they all would be colored red.

To me, this is absolutely amazing. What do you say?

It's worthwhile noting here that <style> can go inside both, <head> and <body>.

In the example above, we had <style> inside <body>, right above the <p> element. However, equally valid would've been the case to put the element in <head>.

Something like this:

HTML
<head>
<style> p { color: red; } </style>
</head> <body> <p>This is a paragraph</p> <p>This is another paragraph</p> </body>

Surprisingly, it doesn't even matter whether the <style> element is before the <p> elements or after it.

Putting <style> before or after given elements to which it applies doesn't matter

Consider the following code:

HTML
<style>
   p { color: red; }
</style>

<p>This is a paragraph</p>
<p>This is another paragraph</p>

Here we have the <style> element before <p> and might think that this establishes the styles first and then later on when we move over to <p>, the styles are already in place and could be applied likewise.

However, this is far from the truth!

For example, the following code has the exact same output as above:

HTML
<p>This is a paragraph</p>
<p>This is another paragraph</p>

<style>
   p { color: red; }
</style>

Here, evidently, the <style> element comes after the elements to which it applies and we might think that it won't have any effect whatsoever.

However, it does. And here's the simple reason for it:

Browsers collect all CSS styles from an HTML document during the HTML parsing stage and then pass this entire chunk to a system which is responsible for applying CSS styles to webpages.

This effectively means that the styling happens completely after the entire HTML has been read.

Therefore, whether a <style> comes before or after the elements it applies to does NOT make any difference at all.

External style sheet

Last but not the least, CSS code can go inside an external style sheet.

An external style sheet is a style sheet defined by a CSS file.

A CSS file has the .css file extension (just like an HTML file has the .html file extension). It represents a style sheet (in that it also generalizes CSS styles for the entire HTML document rather than targeting a particular element).

The term 'external' implies that such a style sheet is not a part of the HTML — that is, the style sheet is not right within the HTML, unlike the style sheet defined by <style> which is, trivially, a part of the HTML.

An external style sheet is linked to an HTML document using the <link> element as follows:

  • The rel attribute, which specifies the relationship of the linked resource, is set to "stylesheet".
  • The href attribute is set to the URI pointing to the style sheet.

Pretty basic.

Time for an example.

Following we have a CSS file named styles.css with the exact same code as in <style> above:

styles.css
CSS
p { color: blue; }

Here's an HTML file greeting.html in the same directory as the CSS file:

greeting.html
HTML
<!DOCTYPE html>
<html>
<head>
   <title>Learning CSS</title>
</head>
<body>
   <h1>Learning CSS</h1>
   <p>This is a paragraph</p>
   <p>This is another paragraph</p>
</body>
</html>

Let's link the CSS file styles.css to this HTML document:

greeting.html
HTML
<!DOCTYPE html>
<html>
<head>
   <title>Learning CSS</title>
<link rel="stylesheet" href="styles.css">
</head> <body> <h1>Learning CSS</h1> <p>This is a paragraph</p> <p>This is another paragraph</p> </body> </html>

Perfect. Let's now see the output produced and witness the moment of truth:

Live Example

Voila! Both the paragraphs are colored red.

Now, with these handful of places to put CSS in, a valid question at this stage would be: Which approach to use?

Well, it depends. The next section goes into detail regarding this.

Which approach to use?

All three of the approaches discussed above to leverage CSS — that is, the style attribute, the <style> element, and an external style sheet — target HTML elements differently.

And this difference largely forms the decision-making process for choosing between each of them.

The style attribute targets an element directly and likewise should be used whenever we wish to style a particular element differently from the rest of the elements on an HTML page.

The style attribute and JavaScript

Perhaps one of the most handy situations for turning to the style attribute to entertain our CSS magic is when we're working with JavaScript.

JavaScript can be used to programmatically and dynamically modify the styles of given HTML elements on a webpage after it has loaded, either upon some interaction or without it.

In this respect, the style attribute is implicitly used to modulate the styles of given elements because it's the most convenient way to do so.

Using a style sheet to specifically style a given element would mean to first only select the element and then apply a declaration block to it. Clearly, this is a lot of work as compared to directly dumping the styles in the style attribute.

Let's say we want to hide a paragraph on a webpage when the user clicks a button.

To achieve this, we simply need a programmatic reference to the paragraph element (more specifically, the paragraph's HTML DOM element) and then apply inline styles to it by setting the style property on it.

The <style> element is useful when we wish to apply a style sheet only to a particular HTML document on a website.

An external style sheet should be used when we wish to apply site-wide styles.

Basically, when CSS styles ought to be repeated on multiple webpages, it makes perfect sense to use an external style sheet.

"Why?" you ask. Let's understand it with an example.

Suppose you have a big website with the same header and footer on all pages. Not surprisingly, you want the same header and footer styles on all pages. Alright. To cater to this need, what you can do is simply put the CSS styles for the header and footer in a seperate file and then refer to that file on all of the webpages (using <link> as we saw above).

This has the immediate consequence that all of your styles are defined in one location. If you need to change something, it has to be done in just one place.

Furthermore, an external style sheet, because it is a separate resource that doesn't change often for most websites, can be cached.

External style sheets and caching

Caching, in the realm of the web, means to store a resource temporarily in memory for quick retrieval on a subsequent request to that same resource.

An external style sheet — or in other words, a CSS file — is a separate resource for the browser to work with; likewise, it could be cached.

Needless to say, this doesn't apply to the <style> element or the style attribute because... well... they both are inside the HTML file (and this then comes down to the caching rule for the HTML file).

This is exceptionally important when it comes to performance optimization for the web, where every second matters in reducing the loading times of websites.

Websites use a combination of all of these approaches depending on the use case at hand. They use:

  • external style sheets to apply styles throughout their website (a collection of numerous webpages);
  • the <style> element to apply style sheets to particular webpages (because using an external style sheet would be an overkill for such cases); and
  • the style attribute to alter the styles of given elements (because, again, using the previous two approaches would be an overkill).

In the coming chapters, we will mostly use the last two ways since they can be used to style multiple elements at once and, more importantly, understand the syntax of style sheets.

Spread the word

Think that the content was awesome? Share it with your friends!

Join the community

Can't understand something related to the content? Get help from the community.

Open Discord

 Go to home Explore more courses