DEV Community

Samuel Grasse-Haroldsen
Samuel Grasse-Haroldsen

Posted on

CSS Selectors

After a suggestion from my mentor on a Firefox issue I'm currently working on, I replaced 20+ lines of JavaScript code toggling a message to 3 lines of CSS. A lot of developers, myself included, can benefit from understanding just how far CSS can take a website.

The Problem

As I mentioned already, the issue I'm working on boils down to displaying a message if the user has no addons and if the user does, hiding that message. To get a working solution I wrote a JS method to create the message and then a method that would toggle the display attribute of the message element. Upon reviewing my code, my mentor suggested using the ~ selector. I had never heard of it so I did some research.

CSS Selectors

I'm was familiar with selecting an element either using the name, id, or class of the element.

/* selects all the p elements */
p {
  color: blue;
}

/* selects all elements belonging to the class error */
.error {
  color: red;
}

/* selects the element with the id green-message*/
#green-message {
  color: green;
}
Enter fullscreen mode Exit fullscreen mode

I also knew about chaining these selectors together.

/* selects all button elements belonging to the warning class */
button.warning {
  background-color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

But I didn't know how many selectors there were and all the possibilities. Here are just a few examples!

/* selects all img elements in the image-container class */
.image-container img {
  margin: 5px;
}

/* selects all img elements that have the image-container class as a parent element */
.image-container>img {
  margin: 9px;
}

/* selects the first img element placed after an element belonging to the image-container class */
.image-container+img {
  margin: 7px;
}

/* selects p elements when user hovers over them */ 
p:hover {
  text-decoration: overline;
}

/* Selects every h2 that comes after a p element */
p ~ h2 {
  color: pink;
}
Enter fullscreen mode Exit fullscreen mode

There are a ton more CSS selectors and you should definitely check them out on w3schools.

Back to Firefox

I've been saving this for last because honestly it was just so mind blowing that I could use a style sheet to accomplish this task. Here it is:

section:not(:empty) ~ #empty-addons-message {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

Now what these selectors do in conjunction is select the element with the id #empty-addons-message that comes after a section element when that section element is not empty. Pretty crazy the kind of logic you can code into your style sheets! Next time you are considering adding some display logic see if you can use CSS to accomplish the task!

Top comments (0)