The internet has changed quite a bit since its early days. One of the biggest differences? How it looks.
In fact, the internet looks so good nowadays that we can forget what websites really are — a bunch of files storing text and media content. In a way, the goal of modern web design is to make us forget that fact and simply enjoy the ride. For that, we have CSS to thank.
After HTML, CSS is the most important language to learn for crafting online experiences. This is because advances in front-end web design over the past few decades have resulted in rising expectations among users. If a website fails to meet our visual standards, it dampens our experience: At best, we assume the organization behind the website is lacking. At worst, we leave the page and never return.
Basically, if content is king, CSS is second-in-command. So, any site owner or web-savvy marketer should at least know the fundamentals.
In this guide, you’ll learn everything you need to know to get started reading and writing CSS, including:
- What CSS is
- The difference between HTML and CSS
- How to write CSS code
- How to link CSS code to your HTML documents
- The important concepts of cascade, specificity, and inheritance
Before continuing, you should understand the basics of HTML. We’ll be talking a lot about elements, tags, classes, and ids — make sure you have these down!
What is CSS?
CSS is a language that defines the design and layout of web pages. In other words, CSS controls how web pages look when loaded in a browser. We call this design and layout the “style” of the page. CSS is the standard language for styling and typically works in conjunction with HTML (the language that defines the content of web pages).
CSS stands for Cascading Style Sheets. “Style Sheets” refers to the CSS document itself, and “Cascading” refers to how style rules are applied to page elements. I’ll explain what that means in more detail later on, but let’s first learn what CSS does.
What is CSS Used For?
Without CSS, the web as we know it would look nothing like it does today. To illustrate, take this HubSpot blog post:
Looks normal, right? But, there’s actually a good deal of CSS being applied to this seemingly basic page. If we disable the CSS that HubSpot applies to the HTML, we see this:
By pulling back the CSS curtain, we see how much it adds to the user experience.
In truth, even the content in the screenshot above has some styling applied to it by the browser. This basic styling, called default styling, makes HTML more legible by adding space between paragraphs and enlarging and bolding headings. Without that, our example looks like this:
Yikes. I don’t care how informative that post is — it looks pretty bad.
The key takeaway here is that CSS exists on virtually every website and is vital to our online experience. CSS lets us style any page element we want, however we want. From color, to typography, to dynamic page layouts, CSS does the heavy lifting.
What is the difference between HTML and CSS?
HTML and CSS go hand-in-hand in building the web pages we know and love. However, these are distinct languages, and it’s important to understand their different purposes.
HTML (Hypertext Markup Language) determines the contents of a web page, including text, links, images, videos etc. An HTML file lists all of the “things” on a page, but it doesn’t specify how these things look when displayed in a browser.
CSS, as we now know, controls the style of these elements. CSS ensures the HTML contents appear to users the way it was intended by designers.
You might be wondering: Why separate these two languages? It’s a reasonable question, since HTML and CSS work together. The answer is that separating style and content makes developing websites much, much easier.
A brief history lesson: When HTML was first introduced in the 1990s, styling was much less of a consideration — the focus was more on just presenting information on a web page. Once developers had that down, the next step was adding rudimentary visual embellishments like colors and fonts.
The first implementation of HTML styling was special HTML tags and attributes that would affect how the text looked. This tacked-on solution worked, but it was far from ideal for designers, especially as websites grew. Those building large online properties had to apply styling to every page element within each HTML file.
You can imagine how this would become a tad maddening. Hence, CSS was created to style HTML without having to change the HTML files directly. Since then, there have been several updates to CSS that add new capabilities — the current standard is CSS3.
Benefits of CSS
As it turns out, there are multiple benefits to separating content code from style code. These include:
- Less coding: Developers can use CSS to apply the same styling to multiple pages and page elements across a website, saving huge amounts of time and reducing the chance of errors. Modifying a site-wide style requires changing just a snippet of code.
- More styling options: You can do a lot with CSS, much more than was permitted by the original HTML styling system. With a clear vision, CSS know-how, and some patience, you can customize a website exactly to your preference.
- Standardization: Since CSS is the uniform language for styling web pages, a developer or designer can understand the styling for any website by looking at the CSS files.
- Better performance: CSS reduces the amount of repetitive styling code. Less code means smaller files, and smaller files mean faster page load times.
How to Write CSS
We’ve explored why the CSS language does and why it’s important (other than what “cascading” means — we’ll get there, trust me). Now, let’s code some.
Those familiar with HTML will notice that CSS syntax looks a little different. Instead of listing page content, CSS lists the style rules that are assigned to HTML elements, an entire HTML document, or even multiple HTML documents. These rules are processed by the web browser loading the HTML file.
A rule in CSS looks like this:
You’ll notice four main components: a selector, declarations, properties, and values. Let’s break down each of these.
What is a CSS Selector?
A CSS rule always begins with a selector. The selector indicates the part of the document where the rule is applied. When processing CSS code, the browser uses the selector to “select” the targeted elements and apply style rules to them. The selector is followed by one or more declarations inside curly braces.
There are a handful of ways to write a selector. The most basic type of CSS selector is the element selector, used in the example above. The element selector targets HTML elements by their names (e.g., p, span, div, a):
See the Pen Element Selector by Christina Perricone (@hubspot) on CodePen.
It is also possible to target an element by its class or id attribute. The class selector is written as a period (.) followed by the class name. The id selector is written as a hash (#) followed by the id name.
See the Pen Class and Id Selectors by Christina Perricone (@hubspot) on CodePen.
To target a specific child element within a parent element, write the selector as the parent element, followed by the child element (with a space in between):
See the Pen Parent/Child Selector by Christina Perricone (@hubspot) on CodePen.
You can even assign the same rule to multiple elements with the grouping selector. The grouping selector comprises two or more element names separated by commas. Order is not important in the grouping selector — the rule will be applied to all listed elements:
See the Pen Grouping Selector by Christina Perricone (@hubspot) on CodePen.
You’ll see these basic selectors all over CSS files, but there are even more selector types that let you target page elements in various ways. To learn more about them, see our guide to CSS selectors.
What is a CSS declaration?
After the selector comes the declaration block, a pair of curly braces containing one or more CSS declarations. A CSS declaration tells the browser how to style the selected element — it consists of a property and a value.
Each declaration ends with a semicolon. Though not required, it’s common to place each declaration on a new line. This practice makes CSS declaration blocks easier for humans to read.
What is a CSS property?
As the first part of a CSS declaration, a CSS property tells the browser what style feature of the element should be changed. There are many CSS properties that affect different things. For example, a property can target an element’s color, size, font, shape, or location on the page. A property is always paired with at least one value. A property and its value(s) are separated by a colon.
Before we talk about values, one important note: For a declaration to take effect, the browser must recognize the property of the declaration. Unfortunately, just because a CSS property exists doesn’t mean it works in every browser. When new properties are introduced, web browsers need to implement them, and some browsers are faster to adopt new CSS features than others.
This is why CSS property reference pages include a “Browser Compatibility” section. For each browser, the chart below lists the earliest compatible release (if available):
Common properties like color and width work on every browser, so you won’t have to worry about compatibility with these properties. When utilizing more obscure properties, however, keep cross-browser compatibility in mind — test your designs in common browsers (as well as desktop and mobile devices) to ensure all visitors will have the same experience.
What is a CSS value?
Every CSS property has its own set of values. The value specifies the styling of an element’s property. Here are some common properties and their values:
- Color-related properties can take simple one-word values like blue and red, as well as hex codes — #33E0FF and #FF5733 — and RGB values — rgb(51, 224, 255) and rgb(255, 87, 51).
- The width property takes can take a length value — px (pixels), for instance — or a percentage, which sizes the element relative to the width of the parent container. For instance, a <div> inside the <body> tag set to 50% width will span half the width of the viewport.
- The font-family property accepts the written names of web-safe fonts like Arial, Times New Roman, or Courier.
See the Pen CSS Values by Christina Perricone (@hubspot) on CodePen.
Some properties accept multiple values. The padding property can take up to four values which set the space above, right of, below, and left of an element’s contents respectively.
See the Pen Span With Padding by Christina Perricone (@hubspot) on CodePen.
You can learn more about how padding and margins work in our guide to the CSS box model.
Like with HTML, you can write comments in CSS. Comments are ignored by the browser and are useful in providing context and notes for your code.
To comment in CSS, write /*, then your comment text, then end with */.
/* I’m a comment in CSS! */
Comments can also be used to test your CSS — to disable a rule or declaration, simply “comment out” the code, then “uncomment” the code to re-activate it:
See the Pen CSS Comments by Christina Perricone (@hubspot) on CodePen.
How to Add CSS to HTML
Of course, CSS doesn’t do us much good if it’s not linked to an HTML file. In this section, I’ll cover three ways to add CSS to HTML: external, internal, and inline.
External CSS exists in its own file. This file is linked to an HTML document with a <link> tag. External CSS is the most common method for adding CSS to HTML, since one external stylesheet can dictate the style of multiple HTML documents. This enables developers to make site-wide changes with just one CSS file.
To create a CSS file, write your CSS code in any text editor or code editor and save the file with the .css extension. To link your CSS file to an HTML file, place your HTML file and CSS files in the same folder, then paste the following code inside the <head> section of the HTML file:
<link rel="stylesheet" target="_blank" rel="noopener" href="style.css">
...where style.css is the name of your CSS file. The rules in this CSS file will apply to any HTML file that references it with the <link> element above.
See the Pen External CSS by Christina Perricone (@hubspot) on CodePen.
Internal CSS is CSS code embedded in an HTML document. It is written inside the <style> element, which is placed in the <head> section:
See the Pen Internal CSS 1 by Christina Perricone (@hubspot) on CodePen.
Internal CSS is best used for small web projects and individual web pages with their own styling. In these cases, it might be easier to keep all your code in the same file, rather than jumping between two — it just comes down to your preference.
Inline CSS is placed inside an HTML tag to change the style of a single specific element. Inline syntax is slightly different than what we’ve seen — the declaration is written as the value of the style attribute:
See the Pen Internal CSS 2 by Christina Perricone (@hubspot) on CodePen.
But hold on...doesn’t this violate the practice of separating style from content? Yes, which is why its use is generally discouraged. Inline CSS is both inefficient to program and harder to understand than external and even internal CSS. Still, it’s good to know in case you ever see it.
CSS Cascade, Specificity, and Inheritance
Up to this point, the concepts we’ve explored so far are relatively straightforward — CSS is a list of style rules applied to HTML. Each rule corresponds to one or more page elements. CSS can be applied externally, internally, or inline. Piece of cake.
However, in your early CSS tinkering, you’ll likely encounter a situation in which your page elements look different than you expect. You’ve written all of your rules correctly and checked for browser compatibility, and your code still doesn’t seem to work. Why is that?
The reason is, in addition to the basic principles we’ve covered, CSS has some built-in systems that control how your code affects page elements. To prevent confusion for your future self, there are three more important CSS terms you should know: cascade, specificity, and inheritance. Let’s unpack each of these.
What is CSS cascade?
Consider the code below. It looks like we have two rules that target the background-color property of the p element. This is a conflict, as the same element can’t have multiple background colors. Which one do you think will apply to p?
See the Pen Cascade Example by Christina Perricone (@hubspot) on CodePen.
In this case, CSS settles on blue because of cascades.
In simple terms, cascade means that CSS considers the order of rules when styling elements. The cascade rule states that if the CSS property of an element is assigned multiple CSS values, the browser will render the value that is processed last. In our example, the value blue was processed after red, so blue applies.
Cascade resolves conflicting rules both within the same style sheet and across multiple style sheets. Rules processed in later stylesheets override conflicting rules in earlier sheets. The cascade rule also applies with respect to internal, external, and inline CSS — inline overrides internal, and internal overrides external. If there’s no CSS applied, the browser default styling takes over.
Cascade is central to how CSS functions — it’s the “C” in CSS. So, make sure you understand it before we proceed.
What is CSS specificity?
Another scenario: Our p tag now has an id. Looking at the CSS, will our paragraph be red or blue?
See the Pen Specificity Example by Christina Perricone (@hubspot) on CodePen.
According to the cascade rule, we should expect the blue value to override red. However, that’s not what we see. Why is that?
The problem in this example is that our CSS selectors are different types, but describe the same element. In cases like this, CSS designates some selectors as “more specific” than others — this is called CSS specificity. Combined with cascade, CSS specificity rules choose which styling to apply in the case of a conflict.
Broadly speaking, CSS says that class selectors are more “specific” than element selectors, and that id selectors are more “specific” than class selector. In the previous example, the first CSS rule uses an id selector. Since id selectors are more specific than element selectors, the red value prevails.
Specificity might seem counterintuitive after learning about cascade. Allow me to clarify: The cascade system takes effect when multiple conflicting rules target the same selector — for instance, if we have two different background-color declarations both using p as their selector.
Specificity is similar to cascade, but different: It takes effect when different selectors are used to target the same page element. If we have two conflicting rules but one uses an id selector and the other uses a class selector, the rule with the id selector will apply because it is more specific.
This can get pretty complex — you could write an entire article on specificity alone. But, for beginners, the best way to learn is by doing. The more CSS you write, the more you’ll encounter and troubleshoot issues involving specificity and cascade.
What is CSS inheritance?
Okay, this one is a bit easier to wrap our heads around. Inheritance means that some CSS declarations applied to an element are passed down to child elements.
We can see inheritance with a property like font-size:
See the Pen Inheritance Example by Christina Perricone (@hubspot) on CodePen.
However, not all properties inherit values from parent elements. Notice how styling is only applied to the parent element above. The font-size declaration is inherited by child divs, while border is not.
Inheritance is another feature of CSS that makes writing code much more efficient. Take fonts, for example. Most websites use a consistent font for all text. Rather than adding the same font-family declaration over and over for every text element on a web page, you can apply the font-family declaration to a high-level element like <body>), and all child elements will take on that font.
In the case that you want to use a different font for a specific child element, you can overwrite inheritance by specifying a different font-family value for the child element:
See the Pen Inheritance Override by Christina Perricone (@hubspot) on CodePen.
One More Example
We’ve seen a lot of examples of CSS rules in action — let’s look at one final example of how several CSS properties combine to create, in this case, a not-too-shabby button element:
See the Pen Final CSS Example by Christina Perricone (@hubspot) on CodePen.
CSS: Program With Style
There you have it — everything you need to know to start whipping up beautiful web pages. For such an influential technology, CSS isn’t too tough to learn, and this knowledge goes an incredibly long way in building websites, tweaking page styles, and troubleshooting common issues.