Simple SPA using only CSS

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Simple SPA using only CSS

Simple SPAs can be created with CSS using the :target selector.

The :target selector fires when the id of an element matches the hash of a url. The hash is everything that comes after #.

The hash.

In this picture, the hash is lesson-plan.

Building a SPA with CSS

We will begin with some sections we want to display to the user. Each section needs an unique id since we’re using the :target selector.

<section id="one"> One </section>
<section id="two"> Two </section>
<section id="three"> Three </section>

We will start by hiding all sections.

section {
  display: none;
}

We need a way for users to select these sections. A simple way is to create a <nav> element that contains a bunch of links. Each link has a href attribute that points to its respective section id.

<nav>
  <a href="one"> One </a>
  <a href="two"> Two </a>
  <a href="three"> Three </a>
</nav>

We can now show the selected section with the :target selector.

:target {
  display: block;
}

Doesn’t this look exactly like a Tab component? Well yes! Tab components can be considered a SPA if they’re the only thing on the page.

Building complex SPAs

You need to be able to manipulate the URL if you want to build complex SPAs. We can do this with location and history, which will be covered in the upcoming lessons.