CSS3 selectors actually select the content we want to style. Obviously a CSS selector is the part of a CSS rule set. Here we will be familiar with the power of basic CSS3 selectors.
At the end of this article, there is a link about more advance CSS3 selectors. I’m sure you will be excited to know about them.
universal, type, id and class selectors
1. * (universal selector)
The universal selector * or wildcard character or star symbol, selects all elements on a page. It targets every single element on the page.
1 2 3 4 | * { margin: 0; padding: 0; } |
Many developers use this trick to zero out the margins and padding. I’d advise you to never use this in production code as it adds too much weight on the browser and is unnecessary. The * can also be used with child selectors.
1 2 3 4 5 | #page * { font-size: 16px; line-height: 20px; color: #ccc; } |
Compatible with: IE6+, Firefox, Chrome, Safari, Opera
2. X (type selector)
type selector must match one or more HTML elements of the same name. So if you need to target all unordered lists, use ul {}
. To state more a selector of nav would match all HTML nav
elements.
1 2 3 4 | ul { list-style: none; margin-left: 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div> <ul> <li>Physics</li> <li>Chemistry</li> <li>Maths</li> </ul> ... <ul> <li>English</li> <li>Spanish</li> <li>French</li> </ul> </div> |
View Demo | Compatible with: IE6+, Firefox, Chrome, Safari, Opera
3. #X (id selector)
To allow a selector to target by id, prefix it by a hash symbol. This is the most common uses.
1 2 3 4 5 6 | #slider { width: 960px; margin: auto; height: 300px; background-color: #000; } |
1 2 3 4 5 6 | <div id="page"> ... <div id="slider"> ... </div> </div> |
id selectors are rigid and don’t allow for reuse. So ask yourself do I absolutely need to apply an id to this element in order to target it? then if possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class. View Demo | Compatible with: IE6+, Firefox, Chrome, Safari, Opera
4. .X (class selector)
The class selector is the most useful of all CSS selectors. Using class selector you can target multiple elements. Use classes when you want your styling to apply to a group of elements.
1 2 3 | .error { color: red; } |
1 2 3 4 5 6 7 8 9 10 11 | <!-- Example 1 --> <div> <span> class="error">this field can't be blank.</span> </div> <!-- Example 2 --> <div> <h2 class="error">Page Not Found</h2> ... </div> |
HTML allows multiple classes to be added to a single element, making class selectors more valuable.
1 2 3 | <div class="box box-border text-center"> ... </div> |
View Demo | Compatible with: IE6+, Firefox, Chrome, Safari, Opera
So here we have come to know about universal, type, id and class selectors and we visited their demo as well. In upcoming articles of this series we will know about power of more advance CSS3 selectors. Check the part 2 here.