3 Advanced CSS3 Techniques You Should Learn

Aug 15 2010 by Max Luzuriaga | 30 Comments

3 Advanced CSS3 Techniques You Should Learn

If you’re reading this, then I can safely assume that you’ve at least heard of CSS3. The latest version of CSS includes properties that allow you to style your HTML elements with rounded corners, drop shadows, and even color gradients.

However, these techniques just scratch the surface of what CSS3 can really do. In this guide, I am going to be talking about three advanced CSS3 techniques.

View Demo

Here is a single demo page of all the code I’ll be using in this guide. It’s best viewed on WebKit browsers (like Google Chrome and Apple Safari) so you can see the CSS3 -webkit animation properties in action.

View Demo

1. Advanced Selectors

One of the most important but under-hyped features of CSS3 is the new advanced selectors. I’m sure I don’t have to tell you why being able to target specific HTML elements without having to use an ID attribute is a good thing!

Traditionally, CSS selectors have always been: IDs (#id), classes (.class), HTML elements (such as p), and occasionally pseudo-classes like :hover or :active.

The problem with this formula is that nearly every element needs to have a hook. This means that to get specific with what you’re selecting, the element needs to have either an ID (if it’s just one element) or a class (if it’s a group of elements) so that the browser knows what you’re talking about.

When you start working with very complex layouts, the amount of IDs and classes you need to add to your markup begins to slow you (and your web pages) down.

Enter CSS3. With numerous new pseudo-classes to choose from, your markup and page response times will thank you.

To demonstrate some of these new selectors, I’ve marked up a simple example: two unordered lists.

<!DOCTYPE html>
<html>
<body>
  <ul>
    <li>First Line</li>
    <li>Second Line</li>
    <li>Third Line</li>
    <li>Fourth Line</li>
    <li>Fifth Line</li>
    <li>Sixth Line</li>
  </ul>
  <ul>
    <li>First Line</li>
    <li>Second Line</li>
    <li>Third Line</li>
    <li>Fourth Line</li>
    <li>Fifth Line</li>
    <li>Sixth Line</li>
  </ul>
</body>
</html>

The following code block is some basic CSS just for visuals. All I’ve done is reset the margins and padding of every element using the universal selector (*) and applied some basic styles to both unordered lists.

* {
  margin: 0;
  padding: 0;
}
ul {
  list-style-type: none;
  margin: 2%;
  border: 1px solid #ccc;
  padding: 5px;
  width: 44%;
  float: left;
}
ul li {
  margin-bottom: 5px;
  padding: 2px;
}

Now it’s time to write our first advanced selector! (Don’t be scared!)

The first part of our selector just says to select the <ul> that is the first child of another element (the <body> in this case).

Then it goes on to select the odd list items (first, third, fifth, and so on) in the first unordered list.

As you can see, using a combination of pseudo-classes and HTML element selectors, we’ve managed to only select the first of the two identical unordered lists.

ul:first-child li:nth-child(odd)

Another way of doing this is shown below, which does the same thing except this time it does so by selecting the first <ul> on the page, regardless of whether or not it’s the first child of another element.

ul:first-of-type li:nth-child(odd)

As you progress further into using CSS selectors, you’ll find that there are many ways of doing the same thing, and it’s up to you to decide which one to use.

With the first unordered list selected, we can style the odd list items (we will give them a different background color than the other list items).

ul:first-child li:nth-child(odd) {
  background-color: #d2fffe;
  border: 1px solid #000;
}

That isn’t the only way of using :nth-child, though. We can also use it to style individual elements based on their position. The code block below gives the 5th list item of the first unordered list on our web page a pink background.

body > ul:first-child li:nth-child(5) {
  background: #ffd2d2;
}

For another example, let’s add a web form to our HTML document. Please note the fact that one of the input elements (name=email) has the Boolean attribute of disabled so that I can demonstrate the :disabled pseudo-class later on.

<form method="post" action="#">
<p>
  <label for="name">Name:</label>
  <input type="text" name="name" value="" />
<p>
  <label for="email">Email:</label>
  <input type="text" name="email" value="" disabled />
</p>
<p>
  <label for="message">Message:</label>
  <textarea name="message"></textarea>
</p>
</form>

The following code block is just some basic styles for our web form. What this will do is remove some default styling on the form and float the labels to the left and the inputs to the right.

form {
  clear: both;
  width: 95%;
}
form p {
  margin-bottom: 15px;
  clear: both;
  overflow: hidden;
}
form label {
  float: left;
}
form input, form textarea {
  width: 70%;
  float: right;
  border: 1px solid #000;
}
form textarea {
  height: 50px;
}

We’re now going to take advantage of the disabled attribute on the email input to add a darker gray background to it.

input:disabled {
  background: #e7e7e7;
}

Next up, we have a complex-looking selector, but it’s actually quite simple.

By using the :not pseudo-class, we are selecting everything inside a paragraph that is also inside a form except for <textarea> and <label> elements.

Essentially, what this will do is target all form fields that aren’t textareas.

form p *:not(textarea):not(label) {
  height: 20px;
}

In actual practice, it would be more efficient to use input as the selector in our particular case, but I chose to do it this way to demonstrate the :not selector and how we can chain different pseudo-classes together to produce a more specific selector.

That’s it for advanced selectors. We covered a lot, but we still have two more techniques to look at! Let’s get started with those.

2. Animations

Animation on the web has long been the domain of Flash and JavaScript. Now, with CSS3, it’s possible to do the same sorts of animation with only a few lines of code!

To demonstrate animation techniques, let’s add another section to our markup: a simple div with no class or ID, and inside it, an <h1> — nothing too fancy.

<div>
  <h1>Hover over to see animation</h1>
</div>

Since it’s our first div, we can use the :first-of-type pseudo-class to select it. I’ve made it a 200px by 200px blue box just to make it easy to see. I’ve also styled the h1 for visuals.

 
div:first-of-type {
  width: 200px;
  height: 200px;
  background: blue;
  color: #fff;
  clear: both;
}
h1 {
  color: #fff;
  font: 30px/1.5 Helvetica, Arial, sans-serif;
  width: 150px;
  margin: 25px auto;
}

3 Advanced CSS3 Techniques You Should Learn

Now comes the fun part! To create the animation, add the following three lines to the div:first-of-type selector. You’ll see nothing yet, but this sets the stage for the animation functionality, which will kick in when the box is hovered on.

-webkit-transition-property: background, border;
-webkit-transition-duration: 2s, 1s;
-webkit-transition-timing-function: linear, ease-in-out;

I’m using three properties to define two animations for the box (background and border). By adding commas between the properties of each option, I can distinguish which ones will be applied to which animation.

The -webkit-transition-property value defines which CSS properties will be animated (background and border).

The -webkit-transition-duration property defines how long the animation transition will be — in this case, 2 seconds for the background and 1 second for the border.

The last -webkit-transition-timing-function tells the browser what equation to use for the transition.

So we’ve set the stage for the animation, but we haven’t added any animation yet!

Let’s fix that by declaring our :hover properties.

div:first-of-type:hover {
  background: #ccc;
  border: 20px solid blue;
}

Now, when you hover over our blue box, the background and border will change and grow. That’s it. We don’t have to add any other code, the animation will run automatically!

We’re not done yet, let’s add one more example animation to the markup.

<div onclick="this.style.webkitTransform='rotate(360deg)'">
  <h1>Click me!</h1>
</div><!--end clickable-->

I’ve used a bit of inline Javascript so that when the div is clicked, it rotates itself around 360 degrees (in production, you will want to do this unobtrusively by using JavaScript DOM selection methods — but that’s out of the scope of this guide).

Next for the CSS, we’ll use the :last-child pseudo-class (since we want to target the last div in our HTML).

div:last-child {
  width: 95%;
  height: 100px;
  -webkit-transition: -webkit-transform 3s ease-in;
  background: rgba(0,0,0,.5);
  cursor: pointer;
}

The things to note about the above CSS code block is that the background property uses the rgba property to give the div a semitransparent background. The other thing to note is the use of the -webkit-transition property shorthand to animate the rotation of the div.

And with that, we’re done with the animation. It’s full steam ahead to the last CSS3 technique we’ll cover: media queries.

3. Media Queries

The third and last advanced CSS3 technique I’ll be discussing is media queries. What are they? Media queries allow web designers to add conditional CSS rules depending on what the user is using to view the web page.

The advantage of this is that we can make new rules on how to display a web page depending on the situation of our user. For example, if their viewport’s width is thinner than 800 pixels, we can adjust the layout accordingly, giving us a truly fluid and flexible layout. So how do we do it? Easy.

@media screen and (max-width:800px) {
  ...properties when browser is 800px or less...
}

If you open up the demo in a web browser that supports media queries, you will see that as you reduce the size of the browser, the boxes change sizes, which is great.

However, wouldn’t it be awesome if when the browser’s width gets reduced, the two lists stop floating? Yes, it would be. And the CSS for that is the following:

@media screen and (max-width:800px) {
  ul {
    float: none;
    max-width: auto;
    width: auto;
  }
}

While we’re at it, let’s make a few other changes. In the following code block, we’ll make it so that the first div disappears if the viewport is less than 800px.

div:first-of-type {
  display: none;
}

Now when the browser is reduced past 800px, the blue box will disappear!

We can even have multiple @media rules in one document. How about we do something else if the browser is lowered to 600px in width?

@media screen and (max-width:600px) {
  ul:last-of-type {
    display: none;
  }
}

Now, when you reduce the browser a little more (less than 600px) — like magic — the second unordered list disappears!

Here’s some styles for when the width is reduced to 400px.

@media screen and (max-width: 400px) {
  div:last-child, form {
    display: none;
  }
  ul:first-of-type {
    height: auto;
    padding: 50px;
  }
  ul:first-of-type li {
    margin-bottom: 50px;
  }
}

I hope you see the potential of media queries, especially with the growing number of ways people view websites (such as through mobile devices).

Wrapping Up

Now you know three advanced CSS3 techniques! Give yourself a pat on the back, you deserve it.

It’s important to note that while the selectors and media queries will work in most modern browsers (Firefox, Safari, Chrome), the animation will only work on Webkit-based browsers like Safari and Chrome.

Further Reading

Related Content

About the Author

Max Luzuriaga is a freelance web designer (see his work on his portfolio site). He’s also a design blogger at The Design Gnome. He likes web standards and loves talking in the third person. Follow him on Twitter as @designgnome.

30 Comments

edurup

August 15th, 2010

Very nice techniques, thanks for sharing.

Anterpreet

August 15th, 2010

CSS3 is amazing. Great guide, thanks :)

Anterpreet

Pontus Ekman

August 15th, 2010

Thank you. I’m really looking forward to CSS3 and HTML5 as the new standard. It’ll open up some really awesome possibilities, especially combined with jQuery and jQuery Mobile. The future will be great!

Take care!

Satya Prakash

August 15th, 2010

I tried checking the Animation by hovering over animation but it does not worked in FF and Chrome. Where does it work.

Datrio

August 15th, 2010

You can also use -moz-transition and -o-transition for all the animations, don’t forget about that! That gets you every new browser, and since IE9 will also support it, use -ms-transition and a normal transition, just for future’s sake.

Parth

August 15th, 2010

A nice read! Thanks

Min

August 15th, 2010

Great tip.thanks

putragaluh

August 15th, 2010

great post, thanks for share

Kayla

August 15th, 2010

All great techniques and very well explained! Definitely looking forward to more CSS3 and HTML5 in future projects. Unfortunately for now I usually stick with the old standby’s because of limited compatibility for now. :( Looking forward to using these more and more regularly in the future though!

Amber Weinberg

August 15th, 2010

CSS3 animations are fun to play with, but since they only work in Safari (and not even in Chrome) you really can’t do too much with it :/

Hinano

August 16th, 2010

@Datrio, thanks for mentioning the extensions for the other browser engines. It’s important to be as inclusive as possible.

A reader

August 16th, 2010

@Satya Prakash: Haha, it’s a bit confusing indeed, but it’s just an image.

Slava Agafonov

August 16th, 2010

Very good article thanks, HTML 5 + CSS is really getting powerful now!

CoryMathews

August 16th, 2010

“* { margin:0; padding:0; }”

*facepalm* stopped reading.

Tobias

August 16th, 2010

Really opened my eyes as what you can do with CSS3, great read!

Jacob Gube

August 16th, 2010

@CoryMathews: *facepalm* CSS reset isn’t the point of the article, learn to think critically.

Rob Jenkins

August 16th, 2010

Max, thanks for the article. Not sure it has illustrated why CSS3 is a step forward, after all webkit isn’t supported by Gecko browsers (Firefox) and probably never will (thanks Datrio for suggesting alternatives). Please don’t tell me CSS3 has introduced browser compatibility issues again (just finished my IE6 counseling). As for hiding elements based on your screen size, be careful. This ideally should be done server side. Hiding content (such as the infamous ‘display:none;’) can get you into deep water with the search engines if not used correctly.

ddeja

August 16th, 2010

Hmm, not sure why so many people is so excited with css3 and html5. Many specialist and im not sure but i thing even W3C says HTML5 will not be ready until 2020, 2022. Could not find similar numbers for CSS3 but first FireFox must be fully compatible than IE and than comes Chrome, Safari, Opera and others… (But maybe until then Chrome will be the leading browser ;))) )

So for now this is just a sample of what can be.
Cheers.

Bryan McAnulty

August 16th, 2010

Nice detailed explanations Max. Personally I haven’t gotten into advanced selectors at all yet. I think it will take a bit of getting used to. As for the rest, we’ve been using bits of CSS3 on every new site we build. It’s awesome how fast CSS3 is catching on.

Arian Xhezairi

August 17th, 2010

“…the animation will only work on Webkit-based browsers like Safari and Chrome.”
That is because -webkit-transition property isn’t a native CSS3 property but it is as you have realized.

CSS3 Transition: http://www.w3.org/TR/css3-transitions/
Chrome 4+, Safari 4+, IE9 and Firefox 4 now support it.

And since when is this valid:
-webkit-transition: -webkit-transform 3s ease-in;

Well done on the advance selectors part anyway.

joel k

August 17th, 2010

no no no
this pseudo classes and animations should not be used to create a design, only to enhance it since its not FULLY supported yet.
thanks Max Luzuriaga for the article, and as you saide in the title
“3 Advanced CSS3 Techniques You Should Learn” Learn no pracgice…

Max Luzuriaga

August 18th, 2010

@Adrian

Sorry for not mentioning it, but everything that is preceded by -webkit or -moz, etc. is a vendor specific prefix (as you’ve obviously realized).

The point of a vendor prefix is to provide vendor specific properties not found in the CSS specification. Obviously this means it will not validate given that the CSS validator checks against the official CSS spec, of which vendor prefixes are not part of.

@Joel

If you wait for every CSS3 property to be *fully* supported, then you’ll be waiting for a very, very long time my friend. The beauty of most new CSS3 properties is that they degrade very gracefully. If a browser does not support border-radius, then the border won’t be rounded, but the page layout will stay the same.

The great thing about animations is that they could be used just as a simple effect, maybe for hover or click. If the browser isn’t webkit, then the hover or click styling will still be applied, there just won’t be any animation.

Granted, most of the pseudo classes and other advanced selectors shouldn’t be used in practice now, given that they do not degrade very gracefully. I just think it’s important that you are ready for when they are fully supported.

Even so, if you’re willing to drop support for some browsers, you can start using these selectors.

The only way to advance web standards is to use them. As I said before, if you wait for total support, you’ll be waiting forever, as neither IE6, 7, or 8, will EVER support CSS3 or HTML5.

Arian Xhezairi

August 18th, 2010

Max, again, I said you are aware of it, just don’t think that nested properties are valid in means of functionality,
[b]-webkit-transition: -webkit-transform 3s ease-in;[/b]

CSS validation isn’t the case this time.
Have a good one.

david

August 19th, 2010

Thanks for posting, really interesting article for the future of web design. Working mainly on commercial web design, everything i do needs to validate, so some of these items will be for personal projects.

Shane

August 19th, 2010

Nice article on CCS3!!! looking forward to when it is more compatible with other browsers in the future!!

Thanks.

Jeff Jones

August 19th, 2010

Will be a learning curve
J

Lisa

August 23rd, 2010

We are really looking forward to HTML5 and CSS3 as the new standards, so these tips help. LT

Alex

September 28th, 2010

don’t work in my newest Mozilla !
:(
What I have to do???

Lukar

January 17th, 2011

Not work in IE8 !!!

Leave a Comment

Subscribe to the comments on this article.