• About
  • Write For Us
  • Contact
  • Top 50 Photography Blogs
  • Resources
  • Forum

IndustryDev

  • Design
    • Photoshop
    • Lightroom
    • Camera Raw
    • Bridge
  • Development
    • HTML
    • CSS
    • Javascript
    • PHP
    • Dev Tools
    • WordPress
  • Photography
  • Blogging
  • Technology
  • Inspiration
You are here: Home / CSS / Learning CSS Selector Basics

Learning CSS Selector Basics

May 31, 2015

Learning CSS Selector Basics

In order to get into CSS a bit more deeply, I think we need to define what it is that we see behind the scenes. What those chunks of code are that we peek at when spying on someone else’s stylesheet. In order to do that, we need to get into what’s called, “CSS syntax.” Not too much – just a bit.

The first things I’d like to cover is what’s called a “CSS rule” (or rule set). Take a look at the following code and I’ll go over it below.

selector { property: value; }

As you may have deduced from the title of this post, we’re going to discuss CSS selectors a lot. Just as luck would have it, the first part of the CSS rule above is just that – a selector. A CSS selector is what we use to select element(s) we’d like to style on a web page. They’re what we use to grab HTML elements, based on their id, class, type, attribute, and more. After we select an element, we can manipulate (style) it in many different ways.

Now, in between the curly braces is what we call the “declaration block.” Declaration blocks encapsulate, yep, you guessed it – declarations. Each declaration is separated by a semicolon and you can include as many declarations as you’d like inside each declaration block.

If you look at the code above one more time, you’ll notice that a declaration is made up of a property name and a value. These two items are separated by a colon. The property is what we would like to style and the value is what we’d like to do to it. So, for example, a property might be a color and a value might be red. We’ll go over this ad nauseam in this and future posts, but for now, take a look at this simple example:

p {
    text-align: center;
    color: red;
}

In the code above, the “p” is the selector. Everything inside the curly braces is part of the declaration block. Inside this block, we’ve got two declarations. In the first declaration, the property is “text-align” and the value is “center.” In the second declaration, the property is “color” and the value is “red.” Notice how the declarations are separated by semi-colons.

If you’re interested in learning more about CSS syntax, you can visit the source over here. Also, if you’d like to get a jump-start on CSS selectors, you can do that here.


Universal Selector

The universal selector is used when you want to select every element on a page. To take advantage of it, you’d need to use the “*” (asterisk) as the selector. It’s a very handy, but quite far reaching selector, so I’d suggest you use is sparingly. Here’s an example of the universal selector in action:

* {
    text-align: center;
    color: red;
}

If you’ll notice, the code example above is almost exactly the same as the one right above it. All I did was change the “p” selector to the “*” selector. While this alteration was small, it can introduce drastic changes.

In the first example with the p selector, the text-align and color properties were limited to paragraphs. Since I changed the p to an * though, those changes would not only apply to the paragraphs, but all other elements.

Type Selectors

Type selectors are probably the lowest hanging fruit out there when it comes to CSS. These types of selectors isolate the actual element, or node, itself. So, if you wanted to style all p tags or div tags or span tags, you would use a type selector. Let’s go over a few examples:


Let’s say that you have this HTML code on your web page:

<body>
    <header>
        <h1>This Is My Heading</h1>
    </header>
        <p>This is a paragraph in the body section.</p>
</body>

You would easily be able to style these elements with the following CSS:

body {
    background-color: #cccccc;
}

header {
    background-color: #ffcccc;
}

h1 {
    color: #ffffff;
    font-size: 24px;
    padding: 10px;
}

p {
    font-size: 18px;
}

So, if you take a look at the code above, you’ll see that we had a few elements in our HTML that were styled in our CSS. This is the base of what we’ll be going over and this is the base of CSS in general. Grab something from your HTML and style it in your CSS. The only thing that gets more complicated than that is what you grab and how you grab it. Of course, the styling options because more plentiful as well, but to get that down, all that’s needed is experience and a bit of ongoing scavenging of information.

ID Selectors

Let’s say we wanted to target something specific on our page to style. If it’s a very narrow styling, we most likely don’t want to use type selectors. What would suit us well is called an “ID selector.”

Every element on an HTML page can have an ID attached to it. It’s the ID that we can target in our CSS file to give styling to. Now, there are a few rules to follow here. We can’t apply more than one ID to an element and IDs must be unique to each web page, meaning we can’t give a div element IDs of “primary” and “main” and then repeat the “main” ID all the way down the page. We have other selectors for that kind of business. Like I said above, ID selectors are very specific.

Let’s take a look at some code, so you know just what I’m referring to. Pretend that I just updated my HTML page with a few columns. I created a “section” element along with an “aside” element. For both of those elements, I assigned IDs of “primary-column” and “secondary-column” respectively.

<body>
    <header>
        <h1>This Is My Main Heading</h1>
    </header>
    <section id="primary-column">
        <h2>This Is My Left Column Heading</h2>
        <p>This is a paragraph in the left column section.</p>
    </section>
    <aside id="secondary-column">
        <h2>This Is My Right Column Heading</h2>
        <p>This is a paragraph in the right column section.</p>
    </aside>
</body>

Now, in order to style those two columns so they format correctly, I had to add some ID selectors to my CSS file. As you can see, to target an ID, you would type a “#” (hash) and then the name of the ID after that. No spaces. After that, style as you would a type selector.

#primary-column {
    width: 70%;
    float: left;
    border: 1px solid red;
}

#secondary-column {
    width: 25%;
    float: right;
    border: 1px solid red;
}

I’m going to give you a small hint here: IDs are very handy when creating an HTML page. They have multiple uses in not only CSS, but HTML page navigation as well as JavaScript. Keep your eye on the ID attribute and learn more about it here.

Class Selectors

Class selectors are similar to ID selectors in that you can apply them to an HTML element. They have one primary difference though. Class selectors can be applied to multiple elements, not just one. In other words, they don’t need to be unique to a page. Also, you are allowed to apply more than one class selector to an element. While I’m not going to give an example of multiple class selectors per element in the example below, I will go over that later on.

Let’s take a look at some code:

<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold">This is a paragraph in the left column section.</p>
</section>
<aside id="secondary-column">
    <h2>This Is My Right Column Heading</h2>
    <p class="bold">This is a paragraph in the right column section.</p>
</aside>


This is the same code as I shared above, but in this code, I added class selectors to both p elements. Basically, I wanted to bold the text within them. Take a look how I styled this in my CSS file:

.bold {
    font-weight: bold;
}

Notice how I used the “.” (period) in front of the selector as opposed to the hash. Just as the word “class” indicates a class in HTML code, a period indicates a class in CSS.

Multiple Classes

Like I mentioned above, more than one class selector can be applied to an element. I gave an example of a class that bolded the text of a paragraph above. Now I’ll give an example of applying two classes to an element. One that bolds the text and one that italicizes it.

<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold italic">This is a paragraph in the left column section.</p>
</section>

Let’s say that we would like to make the bolded text in the primary column not only bold, but italic as well. Since we already have the “.bold” class selector applied to the p element, all we need to do is apply an “.italic” selector to that same class attribute. You can see how I did that in the code above. All we need to do now is create the rule in our CSS file.

.bold {
    font-weight: bold;
}

.italic {
    font-style: italic;
}

And with that, we’ll have a bold and italic paragraph.

Descendant Selectors

This is the first area of CSS that’s going to make you think. While type, ID and class selectors are very straightforward, descendant selectors are more creative.

Descendant selectors are sort of like ID selectors in that they can really drill down into the specificity of styling a document. The way it works is this: say you have two “p” elements, like we do in the above examples. One is contained inside a “section” element and one is contained inside an “aside” element. We only want to style one of the p elements. What do we do? Well, I suppose we could create a class or an ID and apply some styles to it, but we now have another choice as well. Take a look at this:


<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold">This is a paragraph in the left column section.</p>
</section>
<aside id="secondary-column">
    <h2>This Is My Right Column Heading</h2>
    <p class="bold">This is a paragraph in the right column section.</p>
</aside>

This is the same code as I displayed up above. Now, let’s say that we wanted to give a weird olive green background to the paragraph inside the section element. In this case, we could use a “descendant selector” to get the job done. Here’s the code for that:

section p {
    background-color: #cccc00;   
}

Now, the background for only that p element is green. If you’ll notice in the code, all I did was to use the “ancestor” section selector, type a space, and then use the “descendant” p selector and call it a day. If I wanted to, I could have used the ID selector (or a class selector) in the place of the ancestor selector. That would look like this:

#primary-column p {
    background-color: #cccc00;   
}

This would have achieved the same result as using the section type selector. Think of it as a staircase. You start at the top and keep stepping down to get more and more specific. Of course, you don’t want to go overboard because you’ll end up creating a maintenance nightmare. These do have their uses though.

Pseudo-Classes

Pseudo-classes are a keywords added to selectors that specify a special state of the element to be selected. We’ve seen these all over the place. I remember way back when, when I first began discovering the magic of CSS, I wondered how developers made the links on the page change colors when I rolled over them. Well, as it ended up, it wasn’t too difficult.

I’m going to add a link to the first paragraph in our code:

<p class="bold">This is a <a href="#my-link">paragraph</a> in the left column section.</p>

We can do all sorts of things to this link. I’ll show you some CSS code below and then go over what each pseudo-class does.

/* unvisited links */
a:link { 
    color: blue;
} 

/* visited links */
a:visited { 
    color: purple;
} 

/* user hovers */
a:hover { 
    font-weight: normal;
} 

/* active links */
a:active { 
    color: lime;
} 

If you’ll notice in the code above, I added some CSS code that includes pseudo-classes behind the “a” selector. The way to do this is to use a “:” (colon) after the type selector.


I’ve added some random styling to our link. In the first a:link example, I made our link blue on the page. If someone clicks and visits that link, I made it’s “visited” state purple by using the a:visited pseudo-class. After that, I wrote some code that changes the link text from bold back to normal. Do accomplish this, I used a:hover. Finally, I used a:active to change the link color to lime as long as the link is being actively clicked on.

There’s a heck of a lot more to pseudo-classes than I mentioned here, but this is a good start.

Commenting In CSS

If there’s one thing you want to do inside your CSS code, it would be to add comments. This type of code can get extremely long and confusing and by adding comments to it, you can create sections that’ll make life not only much more clear for yourself, but for others who may be working on your code as well.

I added a few comments to the code above. If you take a look, you should see something that looks like this:

/* this is a comment */

Anything inside the /* and the */ will not be interpreted by the browser and is as safe as regular text. You can even write multiple line comments:

/***************************
****************************
this is another comment
****************************
***************************/

You can add comments anywhere you want in your CSS file, such as inside a declaration block:

a:active { 
    color: lime; /* changes active link to lime color */
} 

You can even make the interpreter ignore some of your CSS code by commenting it out:


/*
a:active { 
    color: lime;
} 
*/

Well, that brings us to the close of another post on CSS. If you have any questions or comments, please leave them below. If you want to check out some more CSS related posts, please take a look at my CSS category. Thanks!

Related posts:

  1. Getting a Handle on CSS
  2. Accessing, Changing & Creating DOM Elements in JavaScript
  3. Understanding the CSS Box Model
  4. CSS Values & Units
  5. What is the DOM?

Filed Under: CSS

What’s Next? Email Updates!

If you enjoyed reading this post, why not consider signing up to receive others like it by email? It's so easy and you can unsubscribe at any time.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Connect With Me

  • Facebook
  • Instagram
  • Pinterest
  • RSS
  • Twitter

MOST POPULAR POSTS

  • How to Set the Photo Quality in your Canon Rebel DSLR Camera Before participating in any type of photo shoot, it's i...
  • How to Adjust the Mouse Click & Scroll Settings in Windows 10 I's say this is one of the very first settings I ed...
  • How to Export Video From Adobe Photoshop When it comes to exporting and rendering video clips, t...
  • How to Apply an Adjustment to Only One Layer in Adobe Photoshop The answer is clipping. I'll tell you that right up fro...
  • How to Speed Up & Slow Down Video in Adobe Photoshop This is one of those posts that's going to be super hel...
  • Cutting Out a Shape From a Shape in Adobe Photoshop I've been using shapes for various things in Adobe Phot...
  • How to Set the Self Timer On Your Canon Rebel DSLR Camera Camera self timers are great. I was recently part of a...
  • Animating Scale, Rotation & Opacity in Adobe Photoshop I sat down a few days ago and started messing around in...
  • 3 Ways to Close Applications in Windows 10 This is going to be a very quick post because the topic...
  • How to Set Your Canon Rebel Camera For Continuous Shooting Continuous Shooting mode is very important for those wh...

Recent Comments

  • angelica blanco on How to Organize Video & Audio Project Files for Adobe Photoshop
  • pete salomone on Downloading Photos From a Digital Camera Using Adobe Bridge
  • cdn on How To Create a Slideshow For Your Lock Screen in Windows 10
  • Jay Gaulard on How to Set Your Canon Rebel Camera For Continuous Shooting
  • Deb on How to Set Your Canon Rebel Camera For Continuous Shooting

Copyright © 2021 · IndustryDev.com Web Design & Photography Blog · About · Write For Us · Contact · Privacy / Terms · Sitemap