Special CSS Selectors

Welcome! This post will teach you about CSS selectors that you may not know about. These selectors are not used as often as they should be and are worth knowing how and when you should use them.

I will go through each special selector, explaining how they work, when they should be used and how they can help you become a better developer.

A + B This first selector is refereed to as an adjacent selector. This selector is a great replacement for using the :first-child pseudo element which is not supported in IE 8 and lower without the use of a HTML5 Doctype.

What does it do? Well using the '+' symbol will select only the element that is immediately next to the former element.

Example:

ul + p {
  color: yellow;
}

In the case above only the first paragraph after each ul will have yellow text. Sometimes you might want to select a different paragraph tag next to your ul, to do this you could use the following code which will select a paagraph tag next to your ul seperated by 2 other sibling paragraph tags.

ul + p + p + p {
  color: yellow;
}

A > B The '>' symbol is a very easy selector that you can use instead of adding a class or id to your html to target a certain elements. For example, consider the following markup:

CSS:

div.inner-container > ul {
  border: 1px solid blue;
}

HTML:

<div class="inner-container">
  <ul>
    <li>List Item</li>
      <li>
           <ul>
               <li>
                    Child
               </li>
          </ul>
      </li>
  </ul>
</div>

This selector will only target the ul that is a direct child of .inner-container. It will not target any other ul that is inside .inner-container. This technique is recommended particularly when working with JavaScript-based CSS selector engines.

A ~ B

ul ~ li {
  color: yelow;
}

The sibling combinator above is similar to ul + p, however it is less strict. Instead of selecting the first child of the parent it will select any li tag as long as it is a child of a ul.

a[href="link"]

a[href="http://madaxedesign.co.uk"] {
  text-decoration: underline;
}

This piece of code will style all anchor tags which link to http://madaxedesign.co.uk. A disadvantage of using this is that if you have got a url with .com instead of .co.uk then you'll have to add another selector.

X[href$=".jpg"]

a[href$=".jpg"] {
   color: red;
}

In this case the selector is searching for all anchors which link to an image or at least a url that ends with .jpg. Useful if you want all your anchors linking to a jpg to have a certain style.