Home > Articles

This chapter is from the book

9.7 Advanced Selectors

In order to add an extra bit of polish to the site header, we are going to introduce a few more advanced CSS selectors, and then we’ll continue to add in more styling for the rest of our page. These advanced selectors include pseudo-classes, first-child/last-child, and siblings.

9.7.1 Pseudo-Classes

It’s always nice to have links do something when a user rolls over them, especially since we removed the underlines from the links in Listing 9.16. Those underlines on links are called design affordances, and they are there to give users the suggestion that something will happen if they move the cursor to the link and click.

Some people may argue that all links on a site should have some affordance that clearly marks them as something clickable, either with underlines or by making them look like buttons (HOLY WAR!!!). At this point in time, though, the design convention of putting plain-text links that don’t have underlines (or some other special style) in a header is something that most Internet users are now accustomed to. You just know that the things at the top of the page are clickable.

Without underlines or other immediately visible affordances, though, it is important to show users a response to rolling over the link with their cursor (including on mobile (Box 9.3)). You really want people to know that they are interacting with an element that does something after they perform an action.

All HTML links have a set of what are called pseudo-classes that allow developers to style different interactions with the link:

  • :hover: Styles what happens when a user rolls over the link (applies to any element, not just links)

  • :active: Styles what happens when a user clicks the link

  • :visited: Styles what the link should look like if a user has already visited the linked page

The way to add a pseudo-class to a style declaration is by combining the element or class name with the pseudo-class, like this:

.header-nav a:hover {
  color: #ed6e2f;
}

This use of the :hover pseudo-class arranges to change the color of the link when the user’s mouse hovers over it. (For now we’ve just picked a random orange color that will stand out nicely against the blue background.)

We’ll add a second change as well, which is to make the logo partially transparent on hover using the opacity property. The combined result appears in Listing 9.17.

Listing 9.17: Adding hover states to the navigational links.
css/main.css

.header-nav a:hover,
.header-nav a:active {
  color: #ed6e2f;
}
.header-logo:hover,
.header-logo:active {
  opacity: 0.5;
}

Note that we’ve added the same styling to the :active pseudo-class in order to give mobile users feedback as well (as discussed in Box 9.3).

Save your styles and refresh, and now the nav links will turn orange on rollover, and the logo will turn 50% transparent (the opacity style works like a decimal percentage), as shown in Figure 9.20.

Figure 9.20

Figure 9.20: Muuuuch better.

There are a bunch of other very useful pseudo-classes that are regularly used in designing layouts. We’ll talk about some of these throughout the rest of this section, and we’ll see further examples in Section 13.5.

9.7.2 Exercises

  1. Now that you’ve seen how to style rollovers, try styling the .social-links to have rollover states where the background color changes.

  2. As stated in this section, psuedo-classes like :hover don’t just apply to links. Try adding a hover state that changes the background color of the .full-hero element.

9.7.3 first-child

In order to indicate that the Home link in the navigation menu is particularly important, let’s arrange for it always to be a different color from the others. We could do this with a separate class, but since Home is always going to be the first link in the menu we can target it using what is called the first-child pseudo-class. This pseudo-class applies the corresponding styles only to the first child of the parent element. (There’s also a last-child pseudo-class, which we’ll use in Section 13.4, and many others that are beyond the scope of this tutorial.)

Let’s make the Home link work the opposite of the styling for the other links, so that it’s orange by default and black on rollover. To use the first-child pseudo-class, we need to make sure that whatever we’re targeting is contained in a wrapper, and that there is nothing else in the wrapper. That just means that when you are using the child pseudo-classes, you need the elements to be inside some other HTML element.

If there is anything like text, or an HTML element of a different type, between the top of the parent and the element you are trying to target, the first and last child pseudo-classes won’t work, but in this case we are going to target the first li in .header-nav (Listing 9.18). The ul with the class .header-nav is our wrapper, and the lis are all children that can be targeted.

Listing 9.18: Changing the appearance of just the first link.
css/main.css

.header-logo:hover,
.header-logo:active {
  opacity: 0.5;
}
.header-nav > li:first-child a {
  color: #ed6e2f;
}
.header-nav > li:first-child a:hover {
  color: #000;
}

Note how specific we are in Listing 9.18: We’re using the child selector to target only lis that are direct children of the .header-nav class. You don’t technically need this level of precision, but later on we will add in a dropdown menu in the header (Section 13.4), and if we target styles too generally then we’ll make styling the dropdown difficult.

Now when you save and refresh the first link should look different (Figure 9.21).

Figure 9.21

Figure 9.21: Making the first nav link orange.

9.7.4 Exercise

  1. We mentioned that there are other child selector types. Try out :last-child by changing the color of the link that is in the last li in the page header.

9.7.5 Siblings

Let’s look at two additional advanced selectors, and then after seeing how they work, we’ll use one to add another little style detail to our site navigation. CSS supports two sibling selectors, both of which are written like the child selector > when making a declaration:

  • The adjacent sibling +: Selects a single element only if it is right next to the primary element in the declaration. For example, h2 + p selects a p tag only if it is immediately preceded by an h2 tag.

  • The general sibling ~: Selects all elements of the type in the declaration if they follow the primary element. For example, h2 ~ p applies to all p tags preceded by an h2 tag.

Let’s hop out of working on the header for a second to create an example to use with the sibling selectors. In your default.html file, replace the h2 tag with the HTML from Listing 9.19.

Listing 9.19: Replacing the h2 and adding some text.
_layouts/default.html

<h2>THE FOUNDERS</h2>
<p>
  Learn Enough to Be Dangerous was founded in 2015 by Michael Hartl, Lee Donahoe,
  and Nick Merwin. We believe that the kind of technical sophistication taught by
  the Learn Enough tutorials can benefit at least a billion people, and probably
  more.
</p>
<p>Test paragraph</p>

We can target the paragraph that directly follows the h2 with the style shown in Listing 9.20.

Listing 9.20: Adding an adjacent sibling selector.
css/main.css

h2 + p {
  font-size: 0.8em;
  font-style: italic;
  margin: 1em auto 0;
  max-width: 70%;
  text-align: center;
}

Notice that only the first paragraph is styled (Figure 9.22).

Figure 9.22

Figure 9.22: Only the p immediately after the h2 is styled.

Now if we change to the general sibling selector ~ as in Listing 9.21, both paragraphs will get styled (Figure 9.23).

Listing 9.21: The general selector targets all elements that come after a specified element.
css/main.css

h2 ~ p {
  font-size: 0.8em;
  font-style: italic;
  margin: 1em auto 0;
  max-width: 70%;
  text-align: center;
}

You may also have noticed from Figure 9.23 that the ps in the .bio-boxes below aren’t styled. That is because the sibling selectors don’t pass styles to elements that are wrapped inside any other elements. They only work on elements inside the same parent.

Figure 9.23

Figure 9.23: All p tags after the h2 are now styled the same.

Looking back to the header, we can use a sibling selector in the site header navigation to target all the lis after the first li, and add in a little extra styling to help visually separate the links using the styles in Listing 9.22. You might have seen something like this online: a little vertical line between navigational links to help separate them from other links in a list. Let’s use a sibling selector to add some divider lines.

Listing 9.22: Using the general sibling selector to add styling to the header navigation.
css/main.css

.header-nav > li {
  display: inline-block;
  margin-left: 1em;
}
.header-nav > li ~ li {
  border-left: 1px solid rgba(0, 0, 0, 0.3);
  padding-left: 1em;
}

The rule .header-nav > li ~ li in Listing 9.22 says to apply the subsequent rules to all li elements next to an initial li inside an element with class ”.header-nav”— in other words, every li in the menu after the first one. This way, the divider lines appear before every menu item except the first (Figure 9.24).

Figure 9.24

Figure 9.24: Menu divider lines.

Now that the navigation is fairly spiffy, let’s turn our attention to the logo, which will give us a chance to learn a little bit about CSS positioning.

9.7.6 Exercise

  1. What if you didn’t use the ~ in Listing 9.22, but rather the adjacent sibling selector? Would the divider line appear before every menu item?

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020