logo

CSS Selectors Overview, Part 1

Every CSS rule has two basic parts: a selector and a declaration block. The declaration block lists the formatting instructions like font size, line height, borders, and so on. However, the fundamental part of CSS rule is the selector – after all it tells a web browser to which element or elements on a page these formatting instructions should be applied. Although the original CSS1 specification had only 5 or 6, CSS2 and CSS3 introduced a variety of new selectors enabling complex styling of webpages using simpler CSS and less script. So let’s explore available CSS selectors starting with the most common and simplest and moving onto the more advanced ones.

Universal Selector

The universal selector, denoted by an asterisk, matches any element type in the document. For example, the following rule will reset the default browser padding and margin on every element:

* { margin: 0; padding: 0; }

Attribute selectors

As you may expect from the name, an attribute selector allows you to style an element based on the existence of an attribute or the attribute’s value. Four attribute selectors were introduced in CSS2, and CSS3 added three additional attribute selectors for matching substrings in the value of an attribute.

[attr] – attribute existence

This type of attribute selector matches elements with the specified attribute, regardless of the attribute’s value. The example below selects html5 input elements that have the required attribute:

input[required] { border: 1px solid #f00; }

Compatibility: IE 7+, Firefox, Chrome, Safari, Opera.

[attr=”value”] – exact value

You can select elements that not only share a particular attribute but also have an exact value set for that attribute. For example:

input[type="text"] { padding: 3px; }

This selector matches any input element that has a type attribute with a value equal to text.

Compatibility: IE 7+, Firefox, Chrome, Safari, Opera.



Leave a Reply

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