Papa's Perspective

3 Things You Need to Learn About CSS Selectors

If you haven't checked out CSS, understanding the most often used core selectors is a good place to start.

I want to learn the CSS language, so how do I get started? I hear this question from developers with varying experience. I admit, jQuery makes it awfully easy to locate elements in code, manipulate their styles and toggle CSS classes. But much of the styling can be done directly in CSS, which leads to better separation of concerns.

In CSS, style sheets depend on a cascading order of rules. The selectors indicate the elements that styles are applied to in the markup. One of the easiest ways to get started with CSS is to understand the core selectors, child selectors and descendant selectors. With these three concepts, you can move a lot of styling to CSS and out of your code.

Core Selectors
So where do you start? I recommend learning id, class name and HTML tag selectors first. The id selector matches HTML elements with the same id. It's often used when you want to locate a specific element in the Document Object Model (DOM), and it's easiest to simply give it a unique id. The following CSS applies its styles to the DOM element with the id of tagline:

#tagline {text-align: center; margin-
top: -2%; display: block;}

Id selectors are prefixed with the # symbol. This applies its styles to the following span. The style is applied regardless of the type of HTML element, as long as its id matches the selector:

<span id="tagline">Today's News</span>

Sometimes you just want to style all DOM elements of a specific type. The following CSS is used to style all h1 tags (the most important header) in the page:

h1 {font-family: 'Segoe UI'; padding: 1px; 
text-transform: uppercase; }

This is an excellent way to standardize your fonts, margins and other styles for all elements of a specific type.

You can also create a named class (prefixed with a period) that contains a series of styles. The following class styles all elements that declare its class name:

.callout{font-weight: bold;}

In this example, the .callout class will make the text content bold.

You can style most of your page using these three basic CSS features. However, attaching class names and ids to all of your elements adds a lot of styling constructs to your HTML structure.

Another way to describe class selectors is explicitly named styles. Conversely, implicit styling is when your DOM elements are styled using CSS without requiring class or id names to be littered throughout your structure. But what do you do if you want to style DOM elements of a specific type that exist within a div?

You could add a class to the elements, or you could use descendant selectors. The following CSS will style all h1 elements that exist anywhere inside the header element, directly or several layers deep:

header h1 {   
font-family: 'Segoe UI';   
padding: 1px;   
text-transform: uppercase; }

This is a nice way to style just the h1s inside the header while leaving all other h1 tags alone.

Child Selectors
One common mistake is to use a descendant selector when you really want the CSS to only apply to a direct child of an element.

Child selectors locate elements that are directly beneath them (aka children):

nav > ul > li {   
text-shadow: rgba(0,0,0,.4) 1px 1px 1px;   
text-transform: lowercase;   
font-size: 150%;   
display: inline;   
margin-right: 5%; }

This implicit style will be applied to all li elements that are children of Unordered List (ul) elements that are children of nav elements. Thus, the structure could be written without having to write any styling code in the HTML:

<nav>   
  <ul>     
    <li><a href="#/now" >Now</a></li>     
    <li><a href="#/scores" >Scores</a></li>     
    <li><a href="#/standings" >Standings</a></li>     
    <li><a href="#/statistics" >Statistics</a></li>   
  </ul> 
</nav>

There's so much more to CSS, but if you use the core styling techniques shown here, you can accomplish quite a bit. You can find all of the concepts shown in this article in an example I created using JsFiddle, available at jsfiddle.net/johnpapa/pzczb.

About the Author

John Papa is a Microsoft Regional Director and former Microsoft technical evangelist. Author of 100-plus articles and 10 books, he specializes in professional application development with Windows, HTML5, JavaScript, CSS, Silverlight, Windows Presentation Foundation, C#, .NET and SQL Server. Check out his online training with Pluralsight; find him at johnpapa.net and on Twitter at twitter.com/john_papa.

comments powered by Disqus

Featured

  • Uno Platform Wants Microsoft to Improve .NET WebAssembly in Two Ways

    Uno Platform, a third-party dev tooling specialist that caters to .NET developers, published a report on the state of WebAssembly, addressing some shortcomings in the .NET implementation it would like to see Microsoft address.

  • Random Neighborhoods Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the random neighborhoods regression technique, where the goal is to predict a single numeric value. Compared to other ML regression techniques, advantages are that it can handle both large and small datasets, and the results are highly interpretable.

  • As Some Orgs Restrict DeepSeek AI Usage, Microsoft Offers Models and Dev Guidance

    While some organizations are restricting employee usage of the new open source DeepSeek AI from a Chinese company due to data collection concerns, Microsoft has taken a different approach.

  • Useful New-ish Features in .NET/C#

    We often hear about the big new features in .NET or C#, but what about all of those lesser known, but useful new features? How exactly do you use constructs like collection indices and ranges, date features, and pattern matching?

  • TypeScript 5.8 Beta Speeds Program Loads, Updates

    "TypeScript 5.8 introduces a number of optimizations that can both improve the time to build up a program, and also to update a program based on a file change in either --watch mode or editor scenarios."

Subscribe on YouTube