Chapter 5

Introduction to CSS

In Part I, we learned how to make a simple website using HTML. In Part II, also known as Learn Enough CSS & Layout to Be Dangerous (https://www.learnenough.com/css-and-layout), we’ll learn how to build a more complex website and style it using CSS.

CSS—short for Cascading Style Sheets—is the design language of the World Wide Web. CSS lets developers and designers define what a web page looks like and how it behaves, including how elements are positioned in the browser. Every website that you visit (with some incredibly rare exceptions) uses CSS to make the user experience and interface look inviting, which means that learning the basics of CSS is an essential part of becoming a web developer or designer. It’s also useful for anyone who interacts with developers and designers, which these days seems like practically everyone.

Most CSS tutorials teach the subject in isolation, showing you how to make individual changes to things like text color or font size, without showing you how to put everything together as an integrated whole. This approach is a lot like trying to teach a foreign language by having students read the dictionary. You might learn lots of words, but you would end up with little to no context or ability to have a real conversation (Figure 5.1).1

1. Image courtesy of irantzuarbaizagoitia/123RF.

images

Figure 5.1: You’re not going to learn Spanish from the dictionary alone.

In contrast, Learn Enough CSS & Layout to Be Dangerous is specifically designed to show you how CSS works in the context of a real website.

It’s especially hard to find tutorials that cover how to develop the layout of the page—that is, how one positions elements on the page and determines what content goes where. It’s because this subject is so important—and yet so neglected—that we called this tutorial Learn Enough CSS & Layout to Be Dangerous, rather than simply Learn Enough CSS to Be Dangerous.

Why is layout so often ignored? It’s partially because the layout aspects of CSS can be rather complicated, but it’s also because doing layout well calls for more than plain HTML and CSS. Making a real, industrial-grade website requires using a templating system to assemble the various parts—there are simply too many repeated and custom elements (such as headers, footers, dynamically generated names and dates, etc.) to build such sites by hand (Figure 5.2).

images

Figure 5.2: Most modern websites have many repeated and custom elements.

As a result, even learning enough CSS to be dangerous—that is, enough to accomplish your goals without taking the time to become a complete expert—is far more extensive than most people realize. You need to learn not only the basic CSS rules, but also more advanced rules governing page layout, together with a tool to assemble all the parts into a combined whole.

Learn Enough CSS & Layout to Be Dangerous is designed to fill this need. It fits into the Learn Enough introductory sequence (https://www.learnenough.com/) immediately after Learn Enough HTML to Be Dangerous (https://www.learnenough.com/html) (equivalent to Part I of this tutorial), but it’s also suitable for more experienced developers who want to strengthen their knowledge of web design.2 Among other things, this means that Learn Enough CSS & Layout to Be Dangerous is both a possible prerequisite and also an excellent follow-on to the Ruby on Rails Tutorial (https://www.railstutorial.org/book).

2. Such as, for example, this guy (https://www.michaelhartl.com/).

Because Part II builds on Part I and the material covered in Learn Enough Developer Tools to Be Dangerous, this tutorial is also unusual in that it allows you to deploy the main sample website to the live Web right from the start while following professional-grade development practices throughout. Because of this integrated approach, Learn Enough CSS & Layout to Be Dangerous puts everything together in a way you probably haven’t seen before, even if you’ve previously studied CSS.

5.1 You’re a Front-End Developer

CSS isn’t the kind of language that’s useful to learn in little half-steps—the part that people find difficult is dealing with handling styling when they are deep into creating an honest-to-goodness website with many levels of complexity. The real skill comes in knowing how to plan for a multipage site that uses a bunch of different snippets of code3 placed into a flexible layout that organizes content and data in a useful way.

3. Technically, HTML and CSS are markup and not code, but we’ll sometimes use the latter term as a catchall, especially when discussing principles from coding (such as avoiding repetition) that apply as much to HTML and CSS as they do to programming languages like JavaScript or Ruby.

There are already many sites (like the Mozilla Developer Network CSS Reference) that exhaustively document every CSS property, so going over each and every option from the specification would just be a duplication of effort. Instead, Learn Enough CSS & Layout to Be Dangerous is designed to complement such reference works by showing you how CSS applies to the design of a real website. The resulting narrative explanation gives you the context necessary to understand and apply CSS documentation—especially when combined with a little technical sophistication (Box 5.1).

The important thing at this point in your progress as a developer is to start learning how styling and layout concepts work together, how HTML and CSS combine to make a layout that is actually useful, and how to use some sort of system that allows you to avoid repeating sections of the site or styling on multiple pages (Box 5.2). Doing otherwise would make you an expert at changing text color and size, but you’d have no chance of applying the knowledge you’ve gained to a real-world scenario. In fact, by learning CSS in a holistic way, you’ll not just be getting an introduction to styling—this tutorial is also going to be your first introduction to the world of front-end development.

5.1.1 So, What Is Front-End Development?

When someone says that they are a front-end developer, that means that they work on the parts of a site that people see and interact with. That includes things like HTML, CSS, and JavaScript. You’ll also hear people talk about user interface (UI) design (the way things look) and user experience (UX) design (the way that the interface and different pages function to move users through the site to a goal).

The complement to front-end development is back-end development, which involves the architecture of data, how it is stored, and how it is delivered. Later Learn Enough tutorials (starting with Learn Enough Ruby to Be Dangerous (https://www.learnenough.com/ruby)) cover the basics of back-end development, culminating in the Ruby on Rails Tutorial (https://www.railstutorial.org/), which teaches how to develop a full web application with a database, users, login and authentication, and more.

So, how do we turn an HTML caterpillar into a front-end developer butterfly?

The Plan

We’ll start by building on the styling introduced in Chapter 4. In the final sections of that tutorial, we showed how to add styling directly to elements on a page, while also briefly covering how to factor that styling into a stylesheet. In this tutorial, we’ll expand greatly on this theme.

Throughout the rest of this chapter, we’ll learn the basics of CSS declarations and values by starting with a few super-simple elements on a sample page, with a particular focus on applying the DRY principle (Box 5.2). We’ll end with a first introduction to the essential technique of CSS selectors to target particular page elements for styling.

In Chapter 6, we’ll discuss aspects of selectors that are important to get right at the beginning of a project, with a focus on managing complexity and maintaining flexibility by choosing good names for things (including an introduction to CSS color conventions).

Chapter 7 introduces two of the most important kinds of CSS values: colors and sizes. These lay an essential foundation for Chapter 8 on the box model, which determines how different elements fit together on the page.

In Chapter 9 and Chapter 10, we’ll take the page that we’ve been working on and factor it into a layout using a static site generator (which includes a templating system) called Jekyll to build professional-grade websites that are easy to maintain and update.

In Chapter 11, we’ll learn how to make flexible page layouts using flexbox, adding layouts for a photo gallery page (to be filled in in Learn Enough JavaScript to Be Dangerous (https://www.learnenough.com/javascript)) and a blog with posts. In Chapter 12, we’ll add the blog itself, showing how to use Jekyll to make a professional-grade blog without black-box solutions like WordPress or Tumblr.

Because a large and growing amount of web traffic comes from mobile devices, in Chapter 13 we’ll cover the basics of using CSS and media queries to make mobile-friendly sites without violating the DRY principle (Box 5.2).

As a concluding step in developing the main sample application, in Chapter 14 we’ll add the kinds of little details (like custom fonts and meta tags) that make a site feel complete. The result will be an industrial-strength, nicely styled site deployed to the live Web.

Finally, as a special bonus, we’ll introduce a more recent and advanced layout technique known as CSS grid in Chapter 16. The result is a largely self-contained discussion of how to use grid to accomplish some of the same effects mentioned in previous chapters, as well as some effects specific to grid.

Let’s go!

5.2 CSS Overview and History

CSS takes the form of plain-text declarations inserted into an HTML or CSS file using a text editor (https://www.learnenough.com/text-editor). A typical series of CSS declarations might look like Listing 5.1. (You are not expected to understand these styles at this point.)

Listing 5.1: Typical CSS declarations.

body {
  color: black;
}

p {
font-size: 1em;
}

p.highlighted {
  font-size: 1.5em;
  background: yellow;
}

The “Cascading” part of Cascading Style Sheets refers to the way the defined styles flow, or “cascade”, down from element to element on a page based on a few factors like which declaration came first, whether an element is the child of a parent element that has styles applied to it, or the strength of the declaration (more on this in Section 6.3). This inheritance of style (from the top levels to elements below) happens so that we as developers can avoid having to define how every single element should look. For example, if we changed the color in the body tag in Listing 5.1, that change would cascade down and change the color attribute on every interior element as well.

The “Style Sheet” part of the name (sometimes written as the single word stylesheet) refers to how CSS allows developers to collect all the style declarations in a separate section of the page (called an internal stylesheet), or place them into an external file (called, you guessed it, an external stylesheet). External stylesheets are loaded onto the page as a link in the head section of the HTML. (We’ll learn how to do this ourselves in Chapter 9.) The result is that we end up separating the code that defines how something looks (or is positioned) from the actual content—all of which makes for simpler and more maintainable code.

5.2.1 CSS Is Always Changing

One important thing to note about CSS is that, like HTML, it’s constantly evolving to better serve the needs of web designers and developers. In fact, in many ways CSS is evolving even faster than HTML.

Even though future additions are added to the official CSS specification all the time, they aren’t evenly distributed—when new additions to CSS are proposed, the adoption of those new concepts happens on a browser-by-browser basis. A style that might work in Google Chrome might be totally unsupported by Mozilla Firefox or Microsoft Internet Explorer (or IE’s latest incarnation, Microsoft Edge). Or it’s possible that a given style might be supported, but only if you use a special temporary name to declare the style, a feature that lets developers target only the browsers that support the style they want to use (Box 5.3).

Luckily, at this point the most common styling definitions are essentially the same across different browsers,4 and we aren’t going to cover anything in this tutorial that has questionable browser support. At some point, though, you’ll probably find yourself wanting to use a more cutting-edge style, and when that happens we recommend using a tool like CanIUse to figure out how well-supported the style is. Don’t ever feel self-conscious about using reference sites like that—the fast-changing nature of the language and the spotty browser support make it a necessary tool even for people who have been doing this for years.

4. Anyone who’s spent much time in the world of front-end development can tell you horror stories about when that wasn’t the case (cough IE6 cough).

5.2.2 How Did CSS Develop?

In the beginning, content on the Internet was simply plain text. Then, as methods for organizing content started to come into existence (such as HTML around 1990), a number of methods sprang up to affect the appearance and layout of the data.

At first, many styling solutions that affected how the page looked would be set by individual users’ browser preferences rather than by the creator of the page. As the complexity of the web increased, it became increasingly obvious that there should be a way for the owner of a site to at least suggest how a page should look, rather than leaving the appearance up to each individual browser.

Lots of interesting suggestions were put forward that never got widely adopted, usually because the proposed styling was overly complicated or used a totally nonintuitive structure:

  • Robert Raisch developed RRP, which used arcane two-character style declarations and was fairly unreadable.

  • Pei-Yuan Wei created the ViolaWWW browser and a styling system called PWP, which introduced nesting styles and external stylesheets, but it was only released for Unix operating systems and never really caught on.

  • FOSI was created for an HTML precursor called SGML, and it worked by adding complicated tags on the page around content (not good).

  • DSSSL allowed for complex declarations and was more of a programming language with styling attached, but it had a complicated syntax that made it overly complex for styling.

In short, there was a real Cambrian explosion of proposed standards to make the web pretty, and while some of these systems ended up contributing elements to what became CSS, none of them are direct ancestors (Figure 5.3).5

images

Figure 5.3: There were a lot of precursors to CSS… not all of them successful.

5. Image courtesy of Liliya Butenko/Shutterstock.

About five years after the introduction of HTML, Håkon Lie (working with Bert Bos) put forward a styling system proposal in December of 1996 called CHSS (Cascading HTML Style Sheets). As you might expect, the original proposal has some details that are no longer present in the language, but in his doctoral thesis Håkon Lie simplified the specification into something that more closely resembles modern CSS. Eventually, the concept was adopted by the World Wide Web Consortium (W3C) as the system for styling web content.

Although it represented a big step forward, creating a specification is only half the battle—browsers have to support the standard for it to be of any use to the end-user.

No browser even partially supported CSS until 1997, and there wasn’t full support of the standard in any one browser until March of 2000—partially because browser makers still had their own ideas for how to accomplish styling, and partially because many browsers supported non-standard HTML tags (we’re looking at you, Internet Explorer…).

Each browser handled CSS in its own idiosyncratic way for a long time, and anyone who has been working in front-end development for a while can tell you how maddeningly difficult it was to style a website so that it looked the same across browsers. Microsoft’s Internet Explorer was by far the biggest problem (Figure 5.4), and we can only imagine the number of people who gave up on the world of web design and development thanks to horrific CSS support in early versions of IE.6

6. If you are ever asked to develop something that can work in Internet Explorer 6 or 7, just laugh and walk away. Trying to make a site work on those browsers just isn’t worth it, and thankfully they are finally disappearing from the world.

images

Figure 5.4: You can’t fully understand hate until you try to design for IE6.

The differences between implementations of CSS in different browsers remained significant until just a few years ago, with the rise to dominance of the WebKit browsers (Google Chrome and Apple Safari) and Gecko-powered Mozilla Firefox.

So when reading this tutorial, just keep in mind that styling the Web was a complete and utter mess until very recently—about 15 years after the initial release of the CSS spec in 1997.

5.2.3 The Bog of Eternal Subjectivity

One last bit of meta-information before we jump in and start styling: deciding how to actually implement CSS on a given page can be a confusing mess. Whereas Part I was a little more prescriptive in nature, with many cases where there was only one right way to do things, we are now going to be venturing into places where there is often no right answer. When designing websites with CSS, many solutions to a problem typically exist, which means subjective judgment is the rule rather than the exception (Figure 5.5).7

7. Image courtesy of Historic Collection/Alamy Stock Photo.

images

Figure 5.5: Smell baaaad!

Helping you navigate this mess is where we come in.

Oh, and to make this all a little more fun, you may recall from Box 5.3 that every browser implements some parts of the CSS standard in its own slightly different manner, so you can never be absolutely certain that something will look the same to different users if they are using different browsers… to say nothing of how something will look on different screen sizes and resolutions for different operating systems (Chapter 13).

You have to get used to the idea that no site is going to be exactly the same when viewed by different people. You’ll learn to design (or implement other people’s designs) in a way that allows room for CSS’s inherent ambiguity. Unlike the tightly constrained world of print design, getting things to look exactly the same in every browser and on every operating system is just something you have to give up worrying about.

Additionally, when talking about which CSS rules to use when styling a site or creating a layout, best practices tend to move in fads, or are influenced by the subjective opinion of the developers who worked on a project before you. For example, as discussed in Section 5.5, elements on the page frequently need to be assigned classes or ids, and the way that names are picked is entirely up to the person writing the code. As you might guess (if you know many developers or designers), people have lots of strong opinions on how you should be naming things—a classic holy war situation.8

8. The notion of a technological “holy war” is discussed in Box 5.4 of Learn Enough Developer Tools to Be Dangerous.

The most important thing is to be consistent. If you start a project and do things one way, make sure to keep following the same conventions for the life of the project. Or, if you decide to make a drastic change, spend the next couple of days updating all your old code, for the sake of future developers (including yourself). Keep an eye out in this tutorial for “Style Note” boxes that have tips on what the current best practices are for different uses of CSS.

5.3 Sample Site Setup

Now that we’ve got an overview of the purpose and origins of CSS, it’s time to start looking at some concrete examples. The initial styling rules will necessarily be simple, so it’s important to have patience while we lay this crucial foundation for the working website (with layout) that we’ll be developing starting in Chapter 9.

We’ll start by creating a new project in the repos folder using the same basic mkdir command covered in Section 1.3 (Listing 5.2).9

9. Note for Mac users: Although it shouldn’t matter in Learn Enough CSS & Layout to Be Dangerous, it is recommended that you use the Bourne-again shell (Bash) rather than the default Z shell to complete this tutorial. To switch your shell to Bash, run chsh -s /bin/bash at the command line, enter your password, and restart your terminal program. Any resulting alert messages are safe to ignore. See the Learn Enough blog post “Using Z Shell on Macs with the Learn Enough Tutorials” (https://news.learnenough.com/macos-bash-zshell) for more information.

Listing 5.2: Adding the folder for our sample project.

$ cd                                    # cd to the home directory
$ mkdir -p repos/<username>.github.io   # Make site directory
$ cd repos/<username>.github.io         # cd into new directory

Note that we’ve used a special directory name that corresponds to the main GitHub Pages site for your account:

<username>.github.io

In Listing 5.2, <username> should be replaced with your GitHub username, so the full URL should look something like learnenough.github.io.

GitHub Pages actually supports serving sites out of subdirectories, like learnenough.github.io/sample_css, but unfortunately this solution fails if you have additional subdirectories in your site, such as learnenough.github.io/sample_css/gallery. The reason is that if you include files and images in one subdirectory (e.g., sample_css), there’s no natural way to include the same files and images in further subdirectories (e.g., sample_css/gallery). Since our sample site will eventually have exactly this kind of structure (Section 10.4), we’ve opted to use the root Pages domain. An even better solution is to use a custom domain, which lets you host your GitHub Pages site at a URL like www.example.com; this is the subject of Part III.

To get our site started, we’ll also create an index.html file using the touch command (as discussed in Section 1.3), as shown in Listing 5.3.

Listing 5.3: Adding a blank index.html.

$ touch index.html    # Create an empty index file

Inside the new folder, use your favorite text editor to open the newly created index.html file and paste in the markup shown in Listing 5.4. For convenience, the contents of Listing 5.4 and all other code listings in this tutorial are available online at the following URL:

https://github.com/learnenough/learn_enough_html_css_and_layout_code_listings

Listing 5.4: The initial HTML for our site.
index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page: Don't Panic</title>
    <meta charset="utf-8">
    <style>

    </style>
  </head>
  <body>
    <h1>I'm an h1</h1>
    <ul>
      <li>
        <a href="https://example.com/" style="color: red;">Link</a>
      </li>
      <li>
        <a href="https://example.com/" style="color: red;">Link</a>
      </li>
      <li>
        <a href="https://example.com/" style="color: red;">Link</a>
      </li>
    </ul>
    <h2>I'm an h2</h2>
    <div style="border: 1px solid black;">
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div style="border: 1px solid black;">
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div style="border: 1px solid black;">
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div style="border: 1px solid black;">
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
  </body>
</html>

When you open that HTML document in your browser (if you aren’t sure how to do that, refer back to Section 1.4), you’ll see a series of three red links, some headers, and a series of green links in boxes (Figure 5.6). This will be our initial test page.

images

Figure 5.6: This is the beginning of something great, unassuming though it may seem.

Note: Due to various slight differences between browsers, browser window sizes, etc., your results may not always match the screenshots exactly, so small discrepancies are not a cause for concern. As we’ll emphasize throughout this tutorial, it’s important to focus on achieving good-enough results without chasing the unreachable goal of pixel-perfection.

As in Chapter 1, we’ll deploy our new website immediately to production, which is a good habit to cultivate. First, you’ll need to create a new project at GitHub, using the steps shown in Section 1.3, which in this case looks like Figure 5.7.

images

Figure 5.7: Creating a new GitHub repo.

Once you’ve finished the steps needed to create the repository, initialize and deploy it using the commands shown in Listing 5.5.

Listing 5.5: Deploying the initial site to GitHub Pages.

$ git init
$ git add -A
$ git commit -m "Initialize repo"
$ git remote add origin <repo url>
$ git push -u origin main

If you find the sequence of commands in Listing 5.5 challenging instead of familiar, it’s probably a good idea to review Learn Enough Git to Be Dangerous (https://www.learnenough.com/git) and Section 1.3. (Confirming that the deployment succeeded is left as an exercise (Section 5.3.1).) Finally, although we’ll add in the occasional Git commit/deployment in this tutorial, ultimately these will be up to you, and now is a good time to practice making such decisions on your own (Box 5.1).

5.3.1 Exercise

  1. By visiting the URL <username>.github.io/index.html, confirm that the deployment to GitHub Pages succeeded. Is it necessary to include index.html in the URL?

5.4 Start Stylin’

As discussed in Section 5.2, CSS is a way of defining how elements on an HTML page look and are positioned, with styling that flows (“cascades”) down from element to element based on factors like which declaration came first, whether an element is the child of a parent element that has styles applied to it, or the specificity of the declaration.

So what do “parent”, “children”, and “specificity” mean in the context of a web page and how it gets styled? The idea is that every element on the page is contained inside another element, which in turn can contain other elements—like Russian nesting dolls.

We can visualize the parent and child structure of the elements on a typical page using the diagram in Figure 5.8.

images

Figure 5.8: Relationships always cascade down.

The hierarchical tag structure shown in Figure 5.8 is known as the Document Object Model, or DOM for short.10 Each new level in the DOM is a child of the level above it. In other words, the html tag is the parent of the entire page, the body tag is a child of the html tag, and so on. The body tag then has its own children, which are the h1 and h2 elements, the unordered list ul, and the div elements. In CSS, styling rules flow down from parents to children unless another style interrupts and takes priority.

10. “DOM” is usually pronounced as a word, so “DOM” rhymes with “Mom”.

Our first application of these ideas will be to the repetitive inline styles that exist in our current example page. Now that you know about the DRY principle (Box 5.2), all that redundant styling should be causing a mild case of programmer’s itch, and the only cure is to eliminate the duplication.

If you are reading this after recently finishing Section 4.7, this sort of refactoring should be familiar, though this time through we are going to go a little more into details that weren’t covered before. If literally none of this is familiar, please refer back to Section 4.7.1 and then come back.

Let’s first look at cleaning up the div elements that share identical inline border styling, as seen in Listing 5.6.

Listing 5.6: Repeated inline styles violate the DRY principle.
index.html

<div style="border: 1px solid black;">
<div style="border: 1px solid black;">
<div style="border: 1px solid black;">

To make the example code cleaner, we are going to use the style block that has already been added to our new initial HTML in Listing 5.4 (the best practice is actually to put the CSS rules in a separate file, a task we’ll undertake in Section 9.6).

Now let’s get rid of the repetition in Listing 5.6 by adding in our first CSS declaration, as shown in Listing 5.7.11

11. For simplicity, partial code listings like Listing 5.7 won’t necessarily show the full indentation level, but (as discussed in Box 1.4) you should strive to use the proper indentation level in order to keep your markup tidy.

Listing 5.7: Adding our first CSS style.
index.html

  <style>
    div {
      border: 1px solid black;
    }
  </style>

Figure 5.9 shows the anatomy of the CSS rule from Listing 5.7: the div part of the statement, which is outside the curly braces, is called the CSS selector (in this case targeting only div HTML elements). Then there is a declaration made up of a property (border) and a value (1px solid black) separated from the property by a colon. Finally, there is a semicolon at the end of the line that ends the style. (Just a warning: a lot of these terms get mixed up in regular usage. For example, people will sometimes refer to the whole thing, including the selector, as the declaration.)

images

Figure 5.9: What’s in a name?

Although the spacing shown in Listing 5.7 is typical, CSS is similar to HTML in that whitespace is ignored by the browser. For the sake of any humans viewing your markup, though, it’s a good idea to follow certain formatting conventions (Box 5.4).

After adding the CSS in Listing 5.7, delete all the style=”border: 1px solid black;” attributes from the four div tags (Listing 5.8).

Listing 5.8: How the entire page should now look.
index.html

    <h2>I'm an h2</h2>
    <div>
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/" style="color: green;">I'm a link</a>
    </div>
  </body>
</html>

Save the changes, refresh the page in your browser… and BAM! Everything should look the same. (If not, double-check your work to see if you can get your results to match.)

So what happened here? The declaration that we added in Listing 5.7 is a CSS statement that tells the browser it needs to apply a 1-pixel wide solid black border to all of the divs in the body of the html. (We’ll learn more about pixels in Section 7.3.) The result is a simplification of the code without any change in the page’s appearance.

Now that we’ve seen how to consolidate a bunch of inline styles into a single CSS declaration, let’s do the same thing for the links that are colored red via inline styles inside the lis. First add the new style, as shown in Listing 5.9.

Listing 5.9: Add the new CSS.
index.html

<style>
  a {
    color: red;
  }

And then remove the inline styles from the links:

<li>
 <a href="https://example.com/">Link</a>
</li>
<li>
 <a href="https://example.com/">Link</a>
</li>
<li>
 <a href="https://example.com/">Link</a>
</li>

As before, the appearance shouldn’t change after refreshing the browser.

At this point, we’ve definitely made progress in the fight against inline style redundancy, but what about those links that are colored green at the bottom using inline styling? One way to clean up the inline styles would be to use CSS classes, which we’ll start covering in Section 5.5, but for now let’s see if we can do it with just generic CSS selectors.

Because the links in question are contained inside divs, and the other links on the page are not, we can use the nesting inheritance of CSS to define a style that changes only the color of links inside divs. We can accomplish this by adding a declaration to the style block, and then removing the inline styles from the links on the page. Your entire test page should now look like Listing 5.10.

Listing 5.10: Whole page with new styling to target links inside divs.
index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page: Don't Panic</title>
    <meta charset="utf-8">
    <style>
      a {
        color: red;
      }
      div {
        border: 1px solid black;
      }
      div a {
        color: green;
      }
    </style>
  </head>
  <body>
    <h1>I'm an h1</h1>
    <ul>
      <li>
        <a href="https://example.com/">Link</a>
      </li>
      <li>
        <a href="https://example.com/">Link</a>
      </li>
      <li>
        <a href="https://example.com/">Link</a>
      </li>
    </ul>
    <h2>I'm an h2</h2>
    <div>
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div>
      <a href="https://example.com/">I'm a link</a>
    </div>
  </body>
</html>

The page is a lot cleaner now, isn’t it? Separating the styling from the content makes the page’s code much easier to read, but maybe you can already see the problem with the way that we’ve targeted the styles…

The problem is: if we were to add new divs anywhere on the page, and they happened to have links inside them, those links would be green even if that isn’t what we want. The reason why is that the selector we used in that declaration is way too generic. In Section 5.5, we’ll take a look at how to add styling with far greater specificity using CSS ids and classes.

5.4.1 Exercises

  1. Using what we learned about targeting links inside other objects, change the color of the links inside the lis.

  2. Add a border around the lis using the same styling as we used to add the borders around the divs.

5.5 CSS Selectors

Between Part I and the beginning of Part II, we have so far used only rudimentary targeting techniques for styles. In Part I, we learned how to add styles directly to elements, but this approach is brittle and inefficient. In this tutorial, so far we’ve used CSS that is separated from the content, but we have used only generic selectors like div or a. The problem with generic element selectors is that they apply to all the elements on the page. So, how can we apply styling to specific elements rather than to every single one?

There are two methods, one that targets only one element per page—the id (or “identification”) selector12—and one able to target multiple elements—the class selector. Let’s edit our example HTML to add this kind of targeting to our page.

12. The traditional contraction for “identification” is the uppercase “ID”, but in computer contexts the lowercase “id” has become a common alternative (despite the possible confusion with the psychoanalytic word id). This is due in large part to the convention of using lowercase tags (e.g., div instead of DIV) in modern HTML markup.

Ids and classes are always applied only to the opening tag of an element, and they always have the same format. We’ll use the div tag for concreteness:

<div id="foo" class="bar">
  .
  .
  .
</div>

We see here that both ids and classes consist of key-value pairs, where each value is a string that serves as a label for the id or class. In this case, the key id has value “foo” and the key class has value “bar”.

Although CSS offers a great deal of flexibility in choosing id and class names, there are a few restrictions and usage suggestions:

  • Use only one id per element.

  • No numbers are allowed at the beginning of the name (e.g., name1 is valid, but 1name isn’t).

  • Dashes (-), underscores _, and CamelCase can be used to join multiple words (so foo-bar-baz, foo_bar_baz, and FooBarBaz are all valid names).

  • Spaces are invalid in id names, and are used to separate multiple names in the case of classes (so id=”foo bar” is illegal, while class=”foo bar baz” places three separate classes on an element).

  • Be consistent (e.g., if using dashes as separators, use them everywhere—don’t mix them with underscores unless you have a good reason—see Box 6.1).

To see how this works in practice, let’s add some ids and classes to our sample page. On the first opening div tag that comes right after the h2, add id=”exec-bio”, and then add class=”bio-box” to all of the divs in that section, as shown in Listing 5.11.

Listing 5.11: Adding CSS classes and an id to the sample page.
index.html

    <h2>I'm an h2</h2>
    <div id="exec-bio" class="bio-box">
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div class="bio-box">
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div class="bio-box">
      <a href="https://example.com/">I'm a link</a>
    </div>
    <div class="bio-box">
      <a href="https://example.com/">I'm a link</a>
    </div>
  </body>
</html>

(This use of a class is a good CSS practice, but we generally don’t recommend using an id in this context; we include it here mainly for demonstration purposes. We’ll discuss this issue in more detail in Section 6.2.)

Next, let’s update our CSS block to target these new selectors. To target an id in CSS, you put a # (usually read “hash”) in front of the name, and to target a class you add a . (usually read “dot”). For example, to change the background color of the #exec-bio id, we can use the following CSS rule:

#exec-bio {
  background-color: lightgray;
}

(Here lightgray represents (surprise!) a light gray,13 which is an example of a CSS color name. We’ll cover the details of color naming in Section 7.1.) Similarly, to apply a rule to the .bio-box class,14 we can use the following CSS:

13. CSS supports both the American spelling gray (“a” for “American”) and the English spelling grey (“e” for “English”).

14. We’ll often refer to elements with applied classes using the corresponding CSS notation. In other words, .bio-box refers to an element with the rule class="bio-box".

.bio-box {
  border: 1px solid black;
}

As we’ll see in a moment, this rule keeps the thin black border added in Listing 5.8, but in such a way that it doesn’t apply to all the divs on the site.

Finally, we can target the anchor tags inside the bio boxes using the combination of the class name and the tag name, like this:

.bio-box a {
  color: green;
}

This turns the a tags green, but only if they’re inside an element with class ”bio-box”. This class-based approach gives us much finer-grained control than the method used in Listing 5.10.

Adding these three rules to the style block (while removing the rules we no longer need) leads to the markup shown in Listing 5.12.

Listing 5.12: Adding CSS rules to target the classes and id.
index.html

    a {
      color: red;
    }
    #exec-bio {
      background-color: lightgray;
    }
    .bio-box {
      border: 1px solid black;
    }
    .bio-box a {
      color: green;
    }

After saving your changes and refreshing the browser, you should see that the boxes at the bottom have the same border as before, but now the one with the CSS id has a light gray background (Figure 5.10).

images

Figure 5.10: Elements targeted with classes and ids.

Congrats! You’ve just used ids and classes to target styles at specific elements, and have leveled up your CSS knowledge. Now that you’ve learned how to make declarations, and how to use ids and classes, we can start getting into the nitty-gritty of how CSS works.

5.5.1 Exercises

  1. Try adding a new CSS id to the style section (you pick the name) that sets the background color of an element to orange, and then add that id to one of the links on the page.

  2. Add a new class to the style section (you pick the name again) that changes the background color to azure, and add that class name as a second class on the .bio-boxes. You’ll notice that one box is different from the rest, something that we’ll discuss in Section 6.3.

  3. Commit your changes from this chapter and deploy the result to GitHub Pages. Confirm that the deployed site renders correctly. (It may take a minute or two for the cache to clear, so keep refreshing until the result is what you expect.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.11.89