- Published on
Act with class: CSS Class Selectors
- Authors
- Name
- Yevhenii Airapetian
- @airapetian_dev
Act with class: CSS Class Selectors by Y. Airapetian
Topic: CSS Class Selectors
Author: Y. Airapetian
Estimated Read Time: 11 mins
Contents:
1. Introduction
7. The Task
9. Summary
10. Useful Links
Introduction
In one of the previous posts, we covered the foundations of the tag selectors.
If you need a refresher about the tag selectors check out this post.
Today we'll continue the topic of CSS styling by focusing on another type of selectors - the class selectors.
CSS Class Selectors
How is a class selector different from any other type? You can easily identify it by the following characteristics:
- At the start, there's always a
dot (.)
sign. - A class attribute must have a value that begins with a letter
(a-z, A-Z)
, a hyphen-
, or an underscore_
. - If the class's name starts with a hyphen it must be followed by a letter
(a-z, A-Z)
or an underscore_
. - The length of the class's name must be at least 2 characters.
- The following characters are not allowed when naming the class: ~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ | \ #`
Let's have a look at an example:
.navigation{
display: flex;
flex-direction: row;
}
Here we can see that 2 declarations have been placed inside a class selector with a name navigation.
What does it mean? By this code, we say:
- Find me all elements that have a class
navigation
; - If found, apply to the element(s) the properties/update the properties display and flex-direction with the values of flex and row respectively.
Note 1: If no element is found, no styles will be applied.
Note 2: _The class selector is NOT unique (like an ID selector): if you target a .nav
class, the styles will be applied to ALL classes with this name.
Here's a class selector breakdown:
Figure 1.1: A breakdown of a CSS class selector.
For a class selector to work, we need first to give a certain HTML element a class name. Assuming we have the following markup:
//code before
<nav>
<ul>
<li>
<a href="./home.html" target="_blank">Home</a>
</li>
</ul>
</nav>
//code after
We need to adjust it like this e.g.:
//code before
<nav class="navigation">
<ul>
<li>
<a href="./home.html" target="_blank">Home</a>
</li>
</ul>
</nav>
//code after
Do you notice the difference?
In the second piece of code, the <nav>
tag has a new attribute - a class
with a value of navigation.
Now the styles in our CSS file can properly apply.
But can we add more than 1 class to an HTML tag? Sure we can! The class names, then, need to be separated by a space like here:
//code before
<nav class="navigation menu">
<ul>
<li>
<a href="./home.html" target="_blank">Home</a>
</li>
</ul>
</nav>
//code after
You can apply as many classes as needed (as long as they are separated by a space), however, note that too many classes may complicate code readability and maintenance.
Classes are also widely used in Javascript-based libraries and modules, like React.js and Angular.
Note: Make sure you have a space between the class names. If the names stick together into one word, none of the styles defined in these classes will apply resulting in a possible collapsed look!
Practical use cases
A class selector may be utilized in web development when:
1. We want to mark several tags that perform the same task (grouping) or have common attributes.
Practical use case: This purpose could be grouping the types of elements, such as buttons, with a class .buttons e.g., to give them some general styling, such as widt
h and font-size
.
Figure 1.2: Adding classes to HTML elements.
2. We want to mark one tag for quicker styling or to differentiate it from others.
Practical use case: Returning to our code sample with the <nav>
tag and a class name applied to it, the given class name in this case would greatly simplify styling if we wanted to use other types of selectors, such as the Descendant Combinator. Theoretically, we could have many <nav>
tags in a project with nested <ul>
, <li>
, and <a>
elements. To target a specific <nav>
and its children, a class selector is preferable.
Figure 1.3: Working with classes in an HTML document.
3. Useful to toggle a certain behavior with Javascript.
Practical use case: You can often see it when using a theme switcher on a certain app. By clicking on a light or dark theme, the app changes its looks accordingly.
Figure 1.4: A toggled theme in a navigation bar.
Naming best practices
While it is possible to name a CSS class with any allowed characters, there are several tips for a better web development experience. A class should be:
1. Named semantic, meaning by the role the element performs:
<footer class="footer>
</footer>
<nav class="navigation">
</nav>
2. Consistent naming, meaning adhering to a single naming practice across the project (e.g. BEM).
.article{
}
.article .social-link{
}
.article .internal-link{
}
3. Short and descriptive names.
You may forget about your project for a certain time and as well forget what some piece of code does there. Imagine that another programmer took a look at your codebase and understood without any difficulty what you wanted to achieve with this or that line of code. Use this guide to name your CSS classes.
Otherwise, you risk being this guy:
//not so vivid
.my-btn{
}
//much better
.resume-button{
}
4. Employing prefixes and suffixes.
You can use this method to help group the classes by function or role. This way, you will not confuse one class with another. It may be useful when, e.g. naming various buttons in an app. A bonus to this technique is you can easily find all the relevant elements when searching for them in a code editor.
.button-social{
}
.button-resume{
}
.button-code{
}
5. Avoiding global names.
Your project may contain libraries and modules that work on Javascript. If you give your tags global names like footer or sidebar, these names may conflict with the Javascript module's code and cause bugs.
//not optimal and prone to bugs
.footer{
}
//more descriptive name considering the tag's purpose
.footer-container{
}
You can use the class selector with any available tag in HTML.
Practice Makes Perfect
Are you ready for a little challenge? We're going to practice our knowledge of the class selectors by styling HTML elements.
Preparation Steps
Here's a task overview.
Click on the button below to visit Code Sandbox. It's a coding playground we will use to practice our web dev skills.
Note: Before doing this task it is preferable that you already have some basic knowledge of tag selectors and pseudo-classes and know some common CSS styles.
Explorer
index.html
Preview
Figure 1.5: The CodeSandbox workspace.
If you're logged in, you probably already know what to do. But just in case, go to step 6.
If you're not logged in, you won't be able to edit the files. For this, you need to follow these steps:
- Click on the Sign-in button. You can locate it to the top right of the screen.
Figure 1.6: The CodeSandbox workspace top navigation.
You will be offered a bunch of authorization methods. Click what best suits you but for the purposes of demonstration, we'll stick with the Google authorization method.
- Click on Sign-in with Google button.
Figure 1.7: The CodeSandbox authorization window.
You'll see a field where you need to write your email address.
Note: Here and afterward the login details have been partially shadowed due to privacy reasons.
- Fill in your email address.
Figure 1.8: The Google authorization screen.
If successful, you'll see a password input field.
- Fill in your password details.
Figure 1.9: The Google authorization screen.
If you've done this step, you might be prompted to confirm the login with your smartphone.
- Click to verify the authorization with your smartphone.
Figure 1.10: The Google authorization verification screen.
Then, click confirm on your smartphone. After, click continue or next in your browser if their's a respective pop-up window.
You should now be successfully authorized.
Note: Sometimes it gets buggy so you might have to refresh the CodeSandbox workspace.
Now, you can make a copy of the code to your CodeSandbox account.
- Click on the Fork button. You will find it at the top right of the screen.
Figure 1.12: The CodeSandbox workspace top navigation.
The code will be forked and you can start doing the task.
Note: Just as mentioned before, sometimes it gets buggy so you might need to reload the CodeSandbox workspace.
The Task
Figure 1.13: The done task.
We are interested in the central window marked with a green rectangle and the tab called CSS marked with a blue rectangle.
Figure 1.14: The CodeSandbox workspace.
Here's a simple HTML page that was written for you to focus on the styling part.
It has 5 unstyled buttons with some text.
Right now they look like this:
Figure 1.15: Unstyled HTML buttons.
Your task is to style these buttons according to the guidelines to achieve a result somewhat like below:
Figure 1.16: Final result.
Step 1: Click on the line called CSS in the Explorer section as in the image below:
Figure 1.17: The CSS section of the CodeSandbox workspace.
You will open an empty CSS file where all the styles should be added.
Step 2: Rename the buttons in the HTML file by using a button- prefix;
Step 3: Use a tag selector to style ALL the buttons with the mutual styles. The styles are:
3.1: Set the font size to 18px;
3.2: Set the font family to Arial, Helvetica, sans-serif;
3.3: Set the padding to 6px for top and bottom, and 10px for left and right;
3.4: Set the border's radius is 8px;
Step 4: Style the .resume
button.
4.1: Set the background color to #007791;
4.2: Set the color to white;
4.3: Set the border's color to #015062.
Step 5: Style the .code
button.
5.1: Set the background color to #e8a435;
5.2: Set the border's color to rgb(238, 190, 32);
Step 6: Style the .download
button.
6.1: Set the background color to #9fcb8d;
6.2: Set the border's color to rgb(119, 203, 91);
Step 7: Style the .submit
button.
7.1: Set the background color to #191919;
7.2: Set the color to whitesmoke.
7.3: Set the border's color to rgb(32, 32, 32);
Step 8: Style the .clear
button.
8.1: Set the background color to #fcfcfc;
8.2: Set the border's color to rgb(32, 32, 32);
Step 9: Use the tag selector with a :hover pseudo-class.
(Skip if you don't yet have enough practice with CSS pseudo-classes and the transition property)
9.1: ALL buttons must change their opacity on hover to 0.8.
9.2: The transition of the opacity must take 0.2s with an ease-in effect.
Hit Ctrl + S (Windows) or Command + S (Mac) after each step's point to see the results live on the right screen of the playground:
Figure 1.18: Saving a file in the CodeSandbox workspace.
Note: If you don't know how to complete a certain step, use your Google search skills and research the topic. For example, you may not know what transition
does, so you might want to spend some time researching.
Note 2: You don't need to know all the properties and values at once. The task is to get the feel of the topic and practice troubleshooting. Much of the time, developers work on fixing problems by using their troubleshooting skills which may involve, as you might have guessed, googling!.
Note 3: Once again, don't worry about some properties for now. We will cover them in depth in future posts.
Did you make it to the finish line? If so, congrats! If not, don't worry and head over to the Troubleshooting section below.
Note 4: If you find this task too simple, check out this series of exercises or this one
Troubleshooting steps
If you've tried to complete a certain step or a part of a step, but with no success, here's the basic troubleshooting:
1. Ensure you've written the property right. A CSS color property is not the same as colour.
2. Ensure you've written the value right. A proper value for a CSS font-size property could be 30px but not 30.
3. Ensure you've saved your work by hitting Crtl + S or Command + S.
4. Ensure you're working in the right file. It should be a file with a .css extension.
5. Ensure you've written the class name right. The name of .cleer is not the same as _.clear.
Summary
Today we've covered the basics of the class selectors. We've learned that they can be handy to style certain elements quicker and more efficiently. We've also learned where the class selectors are usually utilized, the naming best practices, applied our knowledge in an exercise, and found out how to troubleshoot our code.
That's a wrap on the basic class selectors.
Till the next time!
Y.A.