Useful tips on CSS selectors

Useful tips on CSS selectors

Blueprint has a great internship program for different disciplines such as SEO, video production, and web development. I myself started out as an intern at Blueprint. The great thing about Blueprint’s internship program is that we take interns of all levels who demonstrate willingness to learn new things.

As a web developer working in front end development, I am passionate about CSS. I have already written other “CSS basics” blog posts on CSS z-index property and CSS box models. One of the very basics of learning CSS for new interns is getting to know how CSS selectors work. CSS selectors are part of the CSS rules that matches elements on a webpage. The CSS selectors allow CSS styles to be applied to all the elements. Today, I am going to share some tips on using CSS selectors.

#foo.bar vs. #foo .bar

One of the things to watch out for when writing CSS selectors is the space between different selectors. Although the two examples look similar, they do completely different things. In the first example, CSS selector is trying to select an element with both an id of “foo” and class of “bar”, like this:

<div id="foo" class="bar">

In the second example, we are trying to select an element with the class of “bar” that is nested inside an element with the id of “foo”, like so:

<div id="foo">
    <div class="bar">
        ...
    </div>
</div>

:first-child vs. :last-child

One of the useful things that come in handy when working with CSS are pseudo classes. For example, :link, :visited, :hover, and :active are all pseudo classes that style links in different states. :first-child is used to select the first child element of a parent element while :last-child is used to select the last child element of a parent element. In my personal use, these pseudo classes are useful in styling navigation. For example, a sidebar navigation may have borders between each item, and you could use these pseudo classes so that the first and/or last elements do not have a top or bottom border applied to them.

However, there are some cross-browser issues with :last-child. This pseudo class does not work in Internet Explorer versions 8 and older. Fortunately, :first-child is compatible with IE versions 7 and newer. To use the border example I gave above, the code may be something like this:

<style>
li { border-top: 1px solid #fff; }
li:first-child { border-top: 0; }
</style>

<ul class="nav">
	<li>First</li>
	<li>Second</li>
	<li>Third</li>
	<li>Fourth</li>
	<li>Fifth</li>
</ul>

In the example above, there will be a 1px white line only between the menu items. The first <li>element will not have a border on top to create this effect.

Conclusion

There are many more CSS selectors that come in very handy in front end development. It is important to know how CSS selectors work and the cross-browser issues, if any, to make beautiful websites for clients.

By: Blueprint

The comments are closed.

No reviews yet