Translate

Friday, May 25, 2012

One Week Away! Drupal Business Summit and Drupal Camp Vancouver





We're ONE WEEK away from the Drupal Business Summit and Drupal Camp events happening here in Vancouver on June 1 & 2! We here at Appnovation are excited, not only because we're gold sponsors of both events, but also because a few of our team members have been chosen to run sessions for Drupal Camp.


Check out what our guys will be talking about:


Scott Bell - Lifecycle of a Drupal Project


Afraaz Ali - The Basics of Multisiting


Adrian Jones - The Drupal User Experience


Jim MacInnes - Drupal and HTML5: Playing Well Together


Both events will be a wealth of information for technical and business people alike looking to learn more about Drupal and what it can do for them.


Register today!





Source : http://appnovation.com//one_week_away_drupal_business_summit_and_drupal_camp_vancouver

Using Contexture links in Drupal 6 & 7





One of the useful improvements in Drupal 7 is contextual links. It allows administrative users the ability to quickly perform tasks related to regions in the page. For example, when you hover your mouse over a block, links are displayed that allow you to click and go to the block configuration page without going through cumbersome Drupal administrative navigation.


In Drupal 6, this module had been recently back ported from D7.


Here are the steps to install it:


Step 1: Download contextual link module from here and place it under the modules folder. In general the folder would be sites/all/module/contextual.


Step 2: Add extra variable to following template files under current theme folder.


- node.tpl.php: $node_classes
- views-view.tpl.php: $views_classes
- block.tpl.php: $block_classes
- page.tpl.php: $page_classes


For example, the line with $node_classes inserted in node.tpl.php should read as:



class="<?php print $classes; ?> <?php print $node_classes;?>"

Step 3: Enable the module and assign 'access contextual links' permission to users.


After that, the contextual links module should be working well for privileged users.


In Drupal 6, contextual links module comes with some default links. You can also add your own task links to the contexture dropdown by implementing hook_contextual_block, hook_contextual_node, hook_contextual_view to make better user experiences.


Here is an example that simply adding ‘Add New Page' to contextual dropdown in particular block.




/**
* Implement of hook_contextual_block
*/

function MODULE_NAME_contextual_block($block) {
$links = array();
$identifier = $block->module .'-'. $block->delta;
switch ($identifier) {
case MODULE_NAME-BLOCK_DELTA:
$links[] = array (
'weight' => 3,
'title' => 'Add New Page',
'href' => 'node/add/page',
'access callback' => 'user _access',
'access arguments' => array(‘create page content’)
);
break;
}
return $links;
}


The MODULE_NAME-BLOCK_DELTA should be replaced by corresponded values respecting block's module & delta key, such as the user login block provided by system module is 'system-0'.


Next time I will show how to customize contextual links in Drupal 7.


Thanks for reading.





Source : http://appnovation.com//using_contexture_links_drupal_6_7

Thursday, May 24, 2012

Typesetting Paragraphs on Web Pages




I don’t know who started it, but at some point in the web’s relatively short history, we decided that paragraphs displayed on web pages should be “typeset” in a manner similar to what we see by default in a Microsoft Word document: an empty line after a paragraph, and no indent for each paragraph.


Somehow it was unanimously settled upon that the traditional manner of typesetting paragraphs — with indents and no spaces between paragraphs — is not as readable on a computer screen. In fact, the default styles applied by a browser on paragraph elements encourages the no-indent method. If you throw together an HTML document that doesn’t have any author styles defined, you’ll see the following when you inspect your paragraph elements in Chrome’s developer tools:


Default paragraph styles in Chrome


As you can see, Chrome automatically sets the top and bottom margins for all paragraphs at 1em. Of course, because of collapsing margins, this means there will be 1em of space between paragraphs, not 2em. And if you know your em units then you know that 1em is, by default, basically equal to 16px, although there can evidently be variations in that.


Thus, Firefox does something similar. Here’s a screen grab from an inspected paragraph with no author styles in Firebug:


Default paragraph styles in Firefox


However, it doesn’t seem that everyone agrees with laying out paragraphs in this no-indent manner on web pages. Let’s first go back to a comment posted by Joe Clark on Jason Santa Maria’s blog. He was writing in response to Jason’s post about the newly released A Book Apart title, CSS3 for Web Designers. Clark said:



Now, I know we’re pals and all that, but books are not Movable Type blog posts and we do not write paragraphs with blank lines between them and no indention. (We are not “typesetting” an O’Reilly “book.”)


Apart from simply being wrong and leading to ambiguities when a paragraph ends a page, I find it induces me to leap to the next graf at the tiniest hint of disinterest.


Do please fix.



Here Clark is talking about the fact that the first release in the A Book Apart series has its paragraphs typeset in the modern format, rather than the traditional indent format.


Jason’s response was, in part:



When I originally set the paragraphs with indents, something about the cadence was off. The paragraphs interspersed with the code didn’t quite have the right rhythm. Combined that with the fact that most of the audience probably does the majority of their reading on webpages, it just made more sense to me to go this way.



Interestingly, Jason seems to have since had a change of heart. Although the first two books in the A Book Apart series (including the online version of book #1) use the modern approach for laying out the paragraphs, the method advocated by Clark was chosen for the rest of the books. However, it looks like all the electronic versions of the books use the modern no-indent method for the paragraphs, as shown in the comparison screen grab below taken from book #5 in the series:


Comparing print vs. e-book


So it seems that Zeldman and company have decided that readability on electronic versions of their books is aided by the modern paragraph style. And as a side point, even the Readability app uses the modern style.


But this valid beef that Clark has about typesetting paragraphs is not limited to the printed page. While reading the comments posted on Zeldman’s Web Design Manifesto 2012 (which, by the way, is a must-read for everyone in the industry), I noticed Clark is now pointing out the same problem in Zeldman’s new design:



I’d like your design better if you and everyone in your company and its band of merry men would learn to typeset paragraphs. Microsoft Word is not a model for such typesetting.



And Clark backs up his words. On his own blogs, he styles his paragraphs in the traditional manner. I don’t see a response from Zeldman on that issue.


Is The Modern Method More Readable?


Look everywhere on the web, and you’ll have a hard time finding a website that lays out its content using traditional paragraph structure with no spaces and indents. Personally, I think Clark makes a valid point in the comment on Jason’s blog. First (in relation to print, although it could happen online too), there is a very real possibility that a single paragraph overflowing to a second page could look like two separate paragraphs. And second, due to the scan-everything nature of hurried readers, which I think we unnecessarily encourage, the gap between paragraphs may very well invite less actual reading.


So after all of this, my question is: Are paragraphs easier to read online when presented in the modern no-indent format? What about E-Books? Does the fact that these are read on a digital screen make the traditional method of setting paragraphs less readable?


I don’t have any definitive answers, and it’s certainly hard to argue with the 99% majority who think the modern method is more readable, but I am considering trying out the traditional method when I redesign this blog. After all, the indent at the start of a traditionally typeset paragraph is precisely what CSS’s text-indent property is for.











Source : http://www.impressivewebs.com/typesetting-paragraphs-web-pages

Project Detritus




Zielun asks of managing projects:



It often happens in projects that based on one, large system with tons of modules that can be enabled or disabled, and documentation is often not up-to-date or doesn`t exist at all. At least I have such experience. I know that real problem lies elsewhere like in project management but such things often plays main role when you or team decides which coding standard to pick for a project to solve such issues.



This project detritus can definitely be frustrating. Big projects that go on for extended periods of time begin looking like sediment layers of a rock formation. It becomes an interesting archaeological expedition as you chip away at the months (and years) of development and can almost pinpoint the time that a chunk of code was written based on the style it was written.


I've rarely seen a long running project maintain an absolutely rigid and consistent coding style. We make mistakes in the course of building a project, correct those mistakes, but rarely go back to correct the ill-conceived approaches used at the beginning of a project.


Nobody wants to clean out the cruft for fear of unsettling the foundation and having the entire project collapse on them.


A modular approach, a good naming convention, and an reduction of element selectors can make it much easier to determine what is and isn't being used on a project. Do a search for a module name and you'll discover right away if it is used and where it is used. Tools can be built to automatically review which classes are being used and which aren't.


This is easier to do if you keep styles in the CSS. Don't keep them inline and don't set them in script.


Why avoid element selectors? HTML can change but it's not as easy to tell if the CSS is being used or not unless you examine every instance. How relevant is #sidebar h2 if I've long since switched level 2 headings to level 3 headings?


To be clear, element selectors can be quite useful. Don't throw out the baby with the bath water. Just strike that balance between when to use an element selector and when adding a class would be cleaner, clearer, and more semantic.


Of course, I talk more about this in a little e-book I wrote...*ahem*




Source : http://snook.ca//archives/html_and_css/project-detritus

CoffeeConsole: A Chrome Extension




Harry Brundage, a co-worker of mine at Shopify, does a lot of CoffeeScript development and said he would love to be able to do CoffeeScript right from the console in Chrome's Web Inspector. I asked Paul Irish, a "dev relations guy" at Google, to point me in the right direction on building just such a thing.


The result of today's pet project is CoffeeConsole, a Chrome extension that adds a new panel inside the Web Inspector. Type in any CoffeeScript and then hit the run button (or hit Command-Enter or Shift-Enter). The code will be compiled into JavaScript and then run in the context of the current window.


I've put together a quick video to demonstrate this.



Behind the scenes, I cobbled together a bunch of resources. Namely, the Ace editor and the CoffeeScript compiler There really wasn't a lot of code that I needed to add except to figure out how to run the compiled JavaScript in the proper context.


There's definitely more features that can (and maybe should) be added such as the ability to review the compiled JavaScript and the ability to view the compilation errors. The project has been added to GitHub, so feel free to contribute. (As of writing this, I still need to choose a license but likely an MIT license.)


Download the extension or check out the repo on Github.



A Call For Better Fragment Identifiers




A Call For Better Fragment IdentifiersWhere would the web be without links? Links are what hold together what we know as the World Wide Web. Without links, the World Wide Web would be more appropriately called the World Wide Set Of Unrelated Pages, or, incidentally, WWSOUP.


While it’s great how simple and effective the process is of “linking” pages together, I think there’s room for improvement.


If you’ve never heard of the term fragment identifier, well, that’s just the official name for the part of a URL that follows the hash symbol (“#”). Some people refer to links with fragment identifiers as “in page links”. So for example, in the following URL, the fragment identifier would be the string “scroll-to-fragid”:




http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#scroll-to-fragid

If you visit the above URL (which is the WHATWG HTML5 spec that discusses fragment identifiers), the page will automatically jump to the section that’s been identified by the browser as the “scroll-to-fragid” section.


Fragment identifiers also come in handy for deep linking and preserving state in Ajax-based applications. So these certainly have an important role on the web.


How Are Fragments Identified?


In order for the browser to correctly identify which section of the page the window should scroll to, the fragment needs to be identified within the HTML by means of the id attribute. This means that if a web developer hasn’t done his job, then there will be no way to link to a specific fragment of any particular document.


So, if you were linking to a document that was five screens long that didn’t have any id attributes in the source, and you wanted to link to a specific section three screens down, you would have no way to do this. You’d have to link to it, then place the words “Scroll down to section B” or something ridiculous like that.


The Problem With Fragment Identifiers


The simple problem that I see with fragment identifiers is that their existence and functionality relies completely on the developer rather than the browser. Yes, the browser needs to read and interpret the identifier and identify the matching fragment. But if the developer doesn’t include any id attributes in the HTML of the page, then there will be no identifiable fragments.


Do you see why this is a problem? Whether the developer has coded identifiers into the HTML has nothing to do with whether or not the page actually has fragments. Virtually every web page has fragments. In fact, sectioning content as defined in the HTML5 spec implies as much. Every element on the page that can contain content can theoretically be categorized as a “fragment”.


So why is it up to the developer (or content creator) to define whether or not a specific portion of the content can be linked to? When any page of content is created, there is no way of knowing which sections of the page are worthy of being identified. The developer or content creator may have a general idea of how a page’s content might be divided up, but ultimately it will be the linking resource that should have full control over what portion of the page they want to highlight.


That, after all, is how linking works. A page that’s displayed as a result of a web-based hyperlink is displayed to the end user only because the referrer (i.e. the page linking to it) defined the link that way. This means that, regardless of what the developer has done behind the scenes in the HTML, all HTML fragments on that page should be identifiable by external referrers.


The Solution: Power to the Browser and User


The solution, as I see it, is for the HTML spec to require that browsers have an internal mechanism for identifying fragments that can optionally be overridden by the developer. Just as the browser, by default, makes all links blue and underlines them, and allows these styles to be changed via CSS, likewise the ability to link to specific sections of a page should be built into the browser, and then the developer should have the option to change this.


Here’s a simple example of how this might be implemented. Suppose you have the following HTML page:



<h1>Page Title</h1>
<p>Some introductory text.</p>

<h2>Page Subhead 1</h2>
<p>Some text for subhead 1.</p>

<h2>Page Subhead 2</h2>
<p>Some text for subhead 2.</p>

<h2>Page Subhead 3</h2>
<p>Some text for subhead 3.</p>

<h2>Page Subhead 4</h2>
<p>Some text for subhead 4.</p>

This type of structure is common on almost all blog posts. The post is divided into sections by means of headings, but unless the developer actually hard-codes id attributes onto each heading tag, there is no way to link to any of those unique sections of the page.


To solve this problem, the browser should allow native fragment identifiers that use the HTML elements themselves in a CSS selector-like fashion. So if you wanted to link to “Page Subhead 3″ in that HTML page, you could do something like this:



<a href="http://www.example.com/example.html#h2:3">Check this out!</a>

Notice the string h2:3 that appears after the hash symbol. This tells the browser to link to the third <h2> element on the page. This example, of course, is just theoretical, and not meant to imply that this is the way it will be implemented. This is just to illustrate how it could be done without being dependent on developer-added attributes.


Why Should Fragments Be Identified By Users?


The reason fragments should be identifiable by users is because a user, not the content creator or the developer, will ultimately decide whether or not a portion of content is valuable or notable in some way.


Yes, the content creator should have the ability to decide how a page is generally divided, if they choose to do so. But the end user should not be restricted from linking to content fragments just because a developer couldn’t be bothered to add id attributes to every element on the page. And that’s besides the fact that it would be a waste of time for a developer to do that or to have to build a CMS that does it automatically.


Blog Comments Get It Right


Linking directly to someone’s blog comment is very useful. Even if a blog doesn’t have an active link for each comment, it’s pretty easy to use developer tools to find the comment’s id and link to it. I’ve done this many times on Smashing Magazine (they don’t have live links on each comment).


If there was no way to link to an individual blog comment, this would be a great hindrance to linking on the web. It would not be enough to link to the “#comments” section and then hope for the best. So CMSs like WordPress do the right thing by dynamically adding a unique identifier to each comment.


As mentioned, this saves the content creator from having to do it themselves, and puts the identifiability (or, the decision on what’s valuable) in the hands of the user or the referring website.


It’s Already in the Works


Being fearful of writing an article like this and having someone smarter poke holes in my proposal, I ran a draft of this piece by Paul Irish and he pointed out that an improvement to fragment identifiers is already in the works, but in very early stages.


A developer named Simon St. Laurent is hosting an “unofficial draft” of a specification called Using CSS Selectors as Fragment Identifiers. The draft is authored by St. Laurent and Eric Meyer and seems to be in the works for about a year (based on the date on that page). There’s even a jQuery script with a GitHub repo that attempts to implement this new type of fragment identifier. (Thanks to Ahmad for the GitHub link.)


And on a related note, media fragments (i.e. deep linking in audio and video, similar to what you can do on YouTube) have now been introduced and have some browser support (evidently WebKit and Firefox). Check out this part of the spec for the syntax.


All credit to Paul Irish for filling me in on these details.


Conclusion


Although implementing better fragment identifiers could be a challenge to support and publicize, for the reasons I’ve explained here, I think it’s a worthwhile addition to the HTML/CSS spec. I’m glad someone is already working on a proposal for this, and I hope this article serves to help make this known so that control of linking to content fragments ends up where it’s supposed to be: in the hands of users.











Source : http://www.impressivewebs.com/better-fragment-identifiers

Callback Functions in JavaScript




Callback Functions in JavaScriptIf you’re fairly inexperienced with JavaScript but you’ve used jQuery, then its likely you’ve used callback functions. But maybe you don’t fully understand how they work or how they’re implemented.


In this post, which is based on what I’ve learned about callback functions, I’ll try to enlighten you on this fairly common JavaScript technique. And maybe some of our JavaScript experts can chime in and let me know what I’ve omitted or oversimplified.


What is a Callback Function?


The above-linked Wikipedia article defines it nicely:



A reference to executable code, or a piece of executable code, that is passed as an argument to other code.



Here’s a simple example that’s probably quite familiar to everyone, taken from jQuery:



$('#element').fadeIn('slow', function() {
// callback function
});

This is a call to jQuery’s fadeIn() method. This method accepts two arguments: The speed of the fade-in and an optional callback function. In that function you can put whatever you want.


When the fadeIn() method is completed, then the callback function (if present) will be executed. So, depending on the speed chosen, there could be a noticeable delay before the callback function code is executed. You can read more about jQuery’s callback functions here.


How to Write a Callback Function


If you’re writing your own functions or methods, then you might come across a need for a callback function. Here’s a very simple example of a custom callback function:



function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}

mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});

Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function. When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.


Notice that the actual parameter is just “callback” (without parentheses), but then when the callback is executed, it’s done using parentheses. You can call this parameter whatever you want, I just used “callback” so it’s obvious what’s going on.


The callback function itself is defined in one the third argument passed to the function call. That code has another alert message to tell you that the callback code has now executed. You can see in this simple example that an argument passed into a function can be a function itself, and this is what makes callbacks possible in JavaScript.


Here’s a JSBin that uses the simple example above.


Make the Callback Optional


One thing you’ll notice about jQuery callbacks is that they’re optional. This means if a method accepts a callback, it won’t return an error if a callback is not included. In our simple example, the page will return an error if we call the function without a callback, like this:



function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}

mySandwich('ham', 'cheese');

You can see this in action here. If you open your developer tools, you’ll see an error that says “undefined is not a function” (or something similar) that appears after the initial alert message.


To make the callback optional, we can just do this:



function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
if (callback) {
callback();
}
}

mySandwich('ham', 'cheese');

Now, since we’re checking to ensure the existence of callback, the function call won’t cause an error without it. You can test this example here.


Make Sure the Callback is a Function


Finally, you can ensure that whatever value is passed as the third argument is in fact a proper function, by doing this:



function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
if (callback && typeof(callback) === "function") {
callback();
}
}

mySandwich('ham', 'cheese', 'vegetables');

Notice that the function now includes a test using the typeof operator, to ensure that whatever is passed is actually a function. The function call has a third argument passed, but it’s not a function, it’s a string. So the test using typeof ensures no error occurs.


Here’s a JSBin with a nonfunction argument passed as the callback.


A Note About Timing


Although it is true that a callback function will execute last if it is placed last in the function, this will not always appear to happen. For example, if the function included some kind of asynchronous execution (like an Ajax call or an animation), then the callback would execute after the asynchronous action begins, but possibly before it finishes.


Here’s an example that uses jQuery’s animate method:



function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);

$('#sandwich').animate({
opacity: 0
}, 5000, function() {
// Animation complete.
});

if (callback && typeof(callback) === "function") {
callback();
}
}

mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});

And again here’s that code live.


Notice that although the callback appears later in source order than the animation, the callback will actually execute long before the animation completes. In this case, solving this problem is easy: You just put the callback execution inside the animate method’s callback function (where it says “Animation complete”).


This doesn’t cover all the details regarding asynchronous functions, but it should serve as a basic warning that callback functions will only execute last as long as all the code in the function is synchronous.


Anything to Add?


For most JavaScript junkies, this is probably pretty easy stuff. So forgive me if you were expecting something deeper — this is the best I can do. :) But if you have anything else to add or want to correct anything I’ve said, please do so.











Source : http://www.impressivewebs.com/callback-functions-javascript

Browser Support for CSS3 Selectors




Browser Support for CSS3 SelectorsNow that the numbers for IE6 and IE7 usage are diminishing rapidly, more and more development teams are starting to weed out support for those older browsers.


Most readers will probably have removed IE6 completely from the equation and soon IE7 will follow. Despite IE8 still having the highest share of any single browser version, the demise of IE6/7 now allows us to be more creative with CSS selectors.


This post will provide a comprehensive review of support for CSS3 selectors in the most troublesome browsers (guess which ones?). Each selector links to the appropriate location in the CSS3 spec.


Selectors Supported in IE7+


Here are the selectors you are limited to using if you support IE7:





























































Selector Name Example
Universal Selector div *
Descendant and Type Selectors div p
article
Class and ID Selectors .example
#example
Chained Classes .another.example
Child Combinator div > p
Adjacent Sibling Combinator div + p
Attribute Selector a[href]
Common Pseudo-classes a:link
a:visited
a:hover
a:active
:first-child Pseudo-class p:first-child
:first-line / :first-letter Pseudo Elements p:first-line
p:first-letter
General Sibling Combinator h2 ~ p
Value Attribute Selectors input[type="text"]
p[class~="example"]
a[hreflang|="en"]
Substring Attribute Selectors img[src^="images/"]
a[href$=".pdf"]
body[href*="home"]

IMPORTANT NOTE: Although the above chart might imply that support for these selectors is flawless in IE7, this is simply not the case. There are many bugs associated with these selectors when used in IE7. You can read a description of most, if not all of them, in SitePoint's selectors reference.


Selectors Supported in IE8+


Unfortunately, IE8 doesn't seem to add much extra but it is much less buggy than IE7. Unless I'm mistaken or have omitted something, here are the selectors supported by IE8 and above:

























Selector Name Example
All the selectors listed in the previous section, but with fewer bugs (See above)
:focus Pseudo-class a:focus
:before/:after Pseudo-elements p:before
p:after
:lang Pseudo-class :lang(fr) > blockquote

Selectors Supported in IE9 / IE10


IE9 adds many more of the new CSS3 selectors Selectors. Support in IE9 and IE10 seems to be identical, aside from maybe a few bugs and inconsistencies. Here’s the list of selectors supported in IE9 and the upcoming IE10, the latter of which is still not a stable release:

















































































Selector Name Example
All the selectors listed in the previous section, but with fewer bugs (See above)
:empty Pseudo-class p:empty
:enabled and :disabled Pseudo-classes input:enabled
input:disabled
:checked Pseudo-class input:enabled
:checked
:first-of-type Pseudo-class li:first-of-type
:last-child Pseudo-class li:last-child
:last-of-type Pseudo-class li:last-of-type
:negation Pseudo-class input:not(type="submit")
:nth-child Pseudo-class p:nth-child(2)
:nth-last-child Pseudo-class p:nth-last-child(2n+1)
:nth-last-of-type Pseudo-class dt:nth-last-of-type(2)
:nth-of-type Pseudo-class img:nth-of-type(2n)
:only-child Pseudo-class p:only-child
:only-of-type Pseudo-class li:only-of-type
:root Pseudo-class :root
::selection Pseudo-element * p::selection
:target Pseudo-class :target
:indeterminate Pseudo-class :indeterminate

* The ::selection pseudo-element has good support in non-IE browsers but, for various reasons, has been removed from the spec.


What About Other Browsers?


As usual, any discussion of “browser support” might as well be called “IE support”, because all the in-use versions of the other browsers have good support for all of the above selectors, and with fewer bugs.


In addition to what’s shown above, there are a number of other CSS3 selectors that are supported by Chrome, Firefox, Safari, and Opera, but have no support in any versions of Internet Explorer. You can see some of these obscure selectors at this MSDN reference (see the “IE9″ column where support is marked “No”) or by browsing the MDN CSS Reference. You can also see many of the non-IE selectors in the CSS3 User Interface Module on the W3C.


Don’t Forget Selectivizr


To add support for various CSS selectors not supported by IE7 and IE8, you can use the Selectivizr JavaScript utility, which adds support for “19 CSS3 pseudo-classes, 2 pseudo-elements and every attribute selector to older versions of IE”.


Conclusion


I haven’t tested all of these. I used a number of different references to compile and find support for what I’ve listed here, but something here could be incorrect. So use this as a guide but test thoroughly (does that even have to be said here?).


Please comment if you know of any major bugs, drawbacks, or corrections worth noting.











Source : http://www.impressivewebs.com/browser-support-css3-selectors

Why Use the Triple-Equals Operator in JavaScript?




“Determining whether two variables are equivalent is one of the most important operations in programming.” That’s according to Nicholas Zakas in his book JavaScript for Web Developers.


In other words, throughout your scripts you’ll probably have lines resembling this:



if (x == y) {
// do something here
}

Or, if you’re conforming to best practices, this:



if (x === y) {
// do something here
}

The difference between those two examples is that the second example uses the triple-equals operator, also called “strict equals” or “identically equal”.


JavaScript beginners who try to adhere to best practices may be using triple-equals and not double-equals, but might not fully understand what the difference is or why it’s important to stick to triple-equals.


What’s the Difference?


In a comparison using the double-equals operator, the result will return true if the two things being compared are equal. But there’s one important catch: If the comparison being made is between two different “types” of values, type coercion will occur.


Each JavaScript value belongs to a specific “type”. These types are: Numbers, strings, Booleans, functions, and objects. So if you try comparing (for example) a string with a number, the browser will try to convert the string into a number before doing the comparison. Similarly, if you compare true or false with a number, the true or false value will be converted to 1 or 0, respectively.


This can bring unpredictable results. Here are a few examples:



console.log(99 == "99"); // true
console.log(0 == false); // true

Although this can initially feel like a good thing (because the browser seems to be doing you a favour), it can cause problems. For example:



console.log(' \n\n\n' == 0); // true
console.log(' ' == 0); // true

In light of this, most JavaScript experts recommend always using the triple-equals operator, and never using double-equals.


The triple-equals operator, as you’ve probably figured out by now, never does type coercion. So whenever you use triple-equals, you’re doing an exact comparison of the actual values. You’re ensuring the values are ‘strictly equal’ or ‘identically equal’.


This means that, using triple-equals, all the examples from above will produce the correct results:



console.log(99 === "99"); // false
console.log(0 === false); // false
console.log(' \n\n\n' === 0); // false
console.log(' ' === 0); // false

What About Inequality?


When doing a not-equals-to expression, the same rules apply. Except this time, instead of triple-equals vs. double-equals, you’re using double-equals vs. single.


Here are the same examples from above, this time expressed with the != operator:



console.log(99 != "99"); // false
console.log(0 != false); // false
console.log(' \n\n\n' != 0); // false
console.log(' ' != 0); // false

Notice now that the desired result in each case should be “true”. Instead, they’re false — because of type coercion.


If we change to double-equals, we get the correct results:



console.log(99 !== "99"); // true
console.log(0 !== false); // true
console.log(' \n\n\n' !== 0); // true
console.log(' ' !== 0); // true

Conclusion


As mentioned, you’ve probably already used triple-equals pretty exclusively. While researching this article, I learned a few things about this concept myself.


I think the best summary comes from Zakas again, where, after recommending always using strict equals, he says: “This helps to maintain data type integrity throughout your code.”











Source : http://www.impressivewebs.com/why-use-triple-equals-javascipt

CSS Specificity Should Be Irrelevant




CSS Specificity Should Be IrrelevantThere have been numerous articles written by some very reputable people discussing the topic of CSS specificity.


I think it’s great if a CSS developer wants to learn the ins and outs of specificity, because it is an important aspect of how CSS works. But I’m going to put forth an argument here that CSS specificity is quite overrated and, in fact, learning about CSS specificity has the potential to degrade the quality of your code.


Who Says Classes Can’t Be Unique?


If you were to ask the average web developer to tell you the difference between a class and an ID, they’d give you the basic answer that I gave in this CSS Basics article: IDs are specific, and can’t be reused; classes are less specific and are reusable.


But many developers have taken this a step further. They reason that since the styles aren’t going to be reused, they advise you to use an ID selector. So IDs are basically reserved for unique styles that won’t apply anywhere else. This sounds fine in theory, but it is bad advice and quite silly really.


There is nothing wrong with using a class that only appears once in your stylesheet. It has basically the same effect as an ID. But when you think of the potential benefits that come from using a unique class, as opposed to a unique ID, there really is no sense in using an ID as the selector.


On its own, .element is exactly the same as #element. It doesn’t matter that the ID selector is more specific, because you’re not trying to override anything anyhow. And on top of that, the class has the potential for later reuse, and will be more likely to keep the natural cascade in place, thus keeping your code cleaner and easier to read and maintain.


Specificity Doesn’t Live in a Vacuum


CSS specificity is always relative to the rest of your CSS, and is not a relevant concept on its own. That’s why thousands of people write CSS every day without knowing much at all about specificity.


If you’ve created clean CSS that isn’t causing specificity wars (yes, this means you have to use OOCSS principles), then there’s no reason to use an ID selector, or any other selector that has high specificity.


It doesn’t matter that #element and !important have really high

specificity


override abilities
. It’s all relative to what else you’re doing in your stylesheet.


For example, compare this code:



.element {
color: blue !important;
background: green !important;
}

.element-2 {
color: blue !important;
background: green !important;
}

.element-3 {
color: blue !important;
background: green !important;
}

With the following one:



.element {
color: blue;
background: green;
}

.element-2 {
color: blue;
background: green;
}

.element-3 {
color: blue;
background: green;
}

Although the exact same selectors are used, and the exact same styles are being applied, it’s obvious that the first chunk of code

is “more specific”


has more weight
than the second. Why? Because each line uses !important. So if these two chunks of code competed with each other, the first one would win, regardless of the cascade.


But why should they compete with each other? They shouldn’t. You should do your absolute best to avoid using !important. Each of those examples, on its own (assuming no other CSS), will produce the exact same result. So specificity

(or weight, in the case of
!important)
is only relative to the rest of your CSS, and is not something that should really affect your CSS development much at all.


If anything, knowing that different selectors have different levels of specificity — which can often be confusing to beginners and even intermediates — should convince you beyond any doubt that OOCSS and its reliance on abstraction and class-based selectors is the superior option.


A Warning About “Learning” Specificity


In the introduction, I said that “learning” about CSS specificity could have a negative impact on your code. The reason I said that is because some may feel that giving styles higher specificity is a good thing. But it’s not.


That’s why I now strongly recommend OOCSS, which encourages using class selectors almost exclusively. Classes have low specificity, and they’re reusable on any element. If instead you choose descendant selectors (like article h2) and ID selectors, then you’re setting your code up to be far less efficient, and with a much higher chance for specificity wars.


Don’t believe me that the simple act of learning specificity can cause problems? Imagine you’re a CSS beginner and you’re creating a new web page. You know nothing about CSS, and think that the class selector is the only selector there is. You’re also aware that you can use multiple classes on a single element, but you don’t know of any other selector. The result? Although you’ll have a lot of classes in your HTML, you won’t have any specificity or cascade problems and your CSS will be easy to maintain. And this will happen even though you know nothing about specificity!


But on the other hand, if you know about varying degrees of specificity, then you’re more likely to use those more specific selectors, and use them improperly, as a crutch. And that’s where problems will arise.


No Blanket Statements


As is always the case, I am not making any blanket statements here; the “it depends” mantra applies here too.


There are rare circumstances where !important is necessary. There are circumstances, contrary to OOCSS thinking, where you have to use a descendant selector. There are cases where you’ve inherited a project and you don’t have the budget to make major changes, and it’s super practical to just use an ID selector. There are instances where a CMS dictates the markup to such an extent that understanding specificity is a huge benefit. And if you’re using a CSS preprocessor, then that could impact a lot of the concepts I’ve alluded to here.


But if you’re creating a project from scratch, and you have full control of the markup, then specificity will not matter. Specificity is under your control, and is always relative to the rest of the CSS. Therefore if you code with one level of specificity in mind in an object-oriented manner, CSS specificity will never be a factor and your code will be much cleaner and easier to maintain.











Source : http://www.impressivewebs.com/css-specificity-irrelevant

CSS3 Box Shadow Syntax Breakdown




This post is just a simple breakdown of CSS3′s box-shadow property, which you can also review on my click chart.


This is mainly written for CSS3 beginners, but does contain some extra info that might be useful to developers already familiar with what’s new in CSS3, including the use of shadows.


The Full Syntax


Here is what a box-shadow declaration looks like, with all the possible values and vendor prefixes included:



.box {
-webkit-box-shadow: #c4c4c4 3px 3px 10px 5px inset;
-moz-box-shadow: #c4c4c4 3px 3px 10px 5px inset;
box-shadow: #c4c4c4 3px 3px 10px 5px inset;
}

You can view the above code in action here.


So what do these values represent?


Value 1: Color


The first value is the color of the shadow. This is any valid color value. The color of the shadow is not naturally semi-transparent, which is a common trait of graphic shadows. But instead, the author has to define a color, along with an optional transparency value, to make the shadow have transparency. For example, you can use HSLA or RGBA color values, both of which allow an alpha channel setting. Or you can just use a fully opaque light grey, like I’m using.


According to the spec, the color value can be omitted and you can define the color of the shadow using the color property. But for some reason, this doesn’t work in WebKit. Other browsers handle this fine, which you can test using this demo.


The color value can be placed after the length values, or before them, but not in between any lengths pairs. So you can’t do this:



.box {
box-shadow: 3px 3px #c4c4c4 10px 5px;
}

The browser will ignore that whole line. So the color value needs to be at the beginning or at the end (assuming you don’t have an inner shadow, discussed below).


Value 2: Horizontal Offset


The next value can be positive or negative, and can be any valid CSS length value. This value specifies the horizontal offset. A positive value pushes the shadow to the right, while a negative value pushes it to the left. This offset is relative to the position of the box on which the shadow is applied.


To show the effect, here is the same shadow from above, but with a 100px horizontal offset.


Value 3: Vertical Offset


The third value is a vertical offset, and has the exact same specs as the horizontal offset, except the shadow will be offset either up or down (i.e. vertically), depending on whether the value is positive or negative.


Again, here is the same shadow, with an added 100px vertical offset.


Value 4: Blur Radius (optional)


The fourth value again uses any valid length value, except this time a negative value has no effect so will be interpreted as “0″. The blur radius defines the sharpness or blurriness of the shadow. The lower the value, the sharper the shadow. A high value will create a large amount of blur.


Here’s an example that has a very high blur radius. And this example shows what happens when the value is negative.


The third length value will always be interpreted as a blur value.


Value 5: Spread Distance (optional)


The next value, another length value, can be either positive or negative, and will define how much the shadow will expand beyond any already-defined offset values. A negative value will make the shadow get smaller, or contract.


This example shows how a large spread distance can appear to negate any offset values. And this example shows the effect of a large spread distance with an inner shadow (more on this below).


Although the blur value is optional, you can’t exclude the blur value if you include the spread, otherwise the spread value will simply be read as a blur value. To fix this, you simply use a value of “0″ for the blur, then include your spread value. So a spread value will never be read unless there are three other length values included.


Value 6: Inset (optional)


This value works similar to an HTML Boolean attribute. In other words, its existence means “use an inner shadow” and its exclusion is interpreted as an outer shadow. So you don’t have to use “outset”, you simply omit it when you don’t want an inset shadow.


The inset value must appear either first or last in the declaration, otherwise the whole line will be negated.


Multiple Shadows


You can apply more than one shadow to a single element simply by comma separating the shadows, within a single box-shadow declaration, like this:



.box {
box-shadow: #c4c4c4 10px 10px 10px 5px, #c4c4c4 30px 20px 10px 10px;
}

Here are some weird staggered multiple shadows.


The shadows are applied from front to back, so the first shadow will overlap the second, the second will overlap the third, and so on. This is the opposite of how HTML elements are stacked with z-index.


Some Final Notes on Box Shadows


Here are some things to note about the implementation of shadows:



  • Browser support is very good, with the only big problems being IE6-8

  • You can polyfill using CSS3 PIE, this script, or cssSandpaper, but you’re probably better off just degrading to no shadow

  • Browsers that require vendor prefixes: Safari 3.1 up to 5.0; Firefox 3.5 and 3.6; Chrome up to version 9; some mobile browsers

  • A large shadow will not push other elements away, nor will it cause scrollbars if it overflows a parent

  • A box shadow will be rounded to reflect any border radius setting, but it will not be affected by a border image

  • As pointed out here, box shadows have the potential to cause performance problems, so use them sparingly











Source : http://www.impressivewebs.com/css3-box-shadow-syntax

CSS: The Bad Parts




CSS: The Bad PartsEvery programming language has its good parts and its ugly parts. CSS (I know, it’s not a programming language, but whatevs) is no different.


In this post, I do nothing but vent. I’ve been coding websites for almost 12 years, and I’ve been doing CSS layouts for nearly half that (yeah, I was a late bloomer). I’ve come to realize what is good and bad about CSS, and here are what I consider “the bad parts”.


The “Standard” Box Model


This has been discussed enough but deserves more ranting. Although we all eventually got used to it, having to recalculate the width of an element every time we wanted to adjust the padding is just awful.


The box-sizing property has helped this along, and with good browser support, and the fact that IE8 supports it, we can finally start to leave the W3C box model behind us.


Font Shorthand


I’ve talked about this before, but what gives with this property? The six properties that can be declared in the font property have no business being in a shorthand value.


For most shorthand properties, shorthand is not a problem. You declare what you want, and if any optionals are omitted, those are set to their initial values. So who cares if they’re reset? For example, anything left out of list-style or background 99% of the time isn’t inheriting anyhow, so it doesn’t matter if the values are reset.


But many typographic properties are expected to inherit values from a parent. So when you use font shorthand, things can get messed up. And if you’re not familiar with the property’s intricacies, you can be left scratching your head.


In other words, if I declare bold text on the <body> element, then I expect it to be bold, even if I use font shorthand.


Floats


Yes, we use them all the time, and we’ve grown accustomed to laying out our pages using the only method we know. But the truth is, float-based layouts have many of the same problems that table-based layouts did — albeit not as large, and with greater benefits.


The main purpose of the float property is to allow inline content to wrap around a floated block-level element. Creating columns using floats is, more or less, a hack. So similar to how we repurposed the <table> element to create entire pages, we’ve likewise repurposed float.


That having been said, floats do not have the accessibility problems, maintenance issues, and performance proplems that table-based layouts do. So we are in much better shape.


But floats are annoying. They cause content to disappear. They require clear fixes. They have been at the core of many IE margin bugs (but that’s obviously more of a vendor issue, but hey, this is a rant, right?). And they don’t do what we really want them to.


Although CSS Regions and flexbox are in the pipeline, it will still be a long time before we’re able to completely abolish float-based layouts and their many quirks.


Vendor Prefixes


Does this one even need an explanation?


IDs as Styling Hooks


Yes, you can still use IDs. But please don’t use them for styling hooks. Many people still don’t agree with me on this. But there is no reason to use them. A class can do anything an ID can do, and with numerous benefits to boot.


IDs should be used almost exclusively for fragment identifiers, and for scripting hooks. So you should still have plenty of IDs in your markup, but my advice is use the class attribute to define your styling hooks, and you’ll magically see your CSS files become a pleasure to work with. And best of all, you can completely forget about the problems of specificity.


Vertical Align


This is one of those properties that sounds so simple. But it’s not. It can come in handy in rare circumstances, but for the most part, it’s not very useful.


The one area where it works very well is on table cells, because it does pretty much what the old valign attribute did, so it’s easy to understand in that context.


But when you consider the fact that vertical-align seems to do something completely different inside a table cell compared to when it’s applied to other elements, well, this makes it one of CSS’s true annoyances.


Collapsing Vertical Margins



Update (March 14, 2012): In the comments
Steven mentions an excellent point about why collapsing margins
are intuitive, contrary to what I said below.

This concept is quite unintuitive, and I don’t know the reason it happens. But basically, in certain specific circumstances, if the bottom margin of a block element is touching the top margin of another block element, the smaller of the two margins will collapse to zero.


And there’s a whole slew of gotchas and whatnot that help you to understand when this happens, and when it doesn’t. The good thing is, it generally doesn’t pose a problem. But in those rare cases, it does seem bizarre to negate, for no apparent reason, something that is explicitly defined by the page author.


Width: 100%


Similar to vertical-align, this is another one of those CSS techniques that doesn’t do what we want it to do. However, when you understand how percentages work in CSS, it’s not a very difficult concept to get used to.


When beginners start using CSS and they want a box to fill some horizontal space, their first reaction is to try “width: 100%”. It sounds like it’s going to cause the element to fill the remaining space, and there will be no need for calculating the width. But that’s not what 100% does.


Percentages in CSS are always relative to other settings in your CSS (like a parent element). “Width: 100%” actually does exactly what it sounds like it does. It doesn’t fill “100%” of the remaining space; it fills 100% of all the space, besides any margin and padding settings.


So this property/value pair will often have undesirable results, which is probably why it’s not used very often.


Border Images


Of all the new CSS3 features, I have a feeling this one will be one of the most unused and ignored. I wrote an article for SitePoint to try to promote it as a useful technique, because most of the examples I’d seen using border-image were so ugly.


But more and more I’m starting to think that I’ll never use this property, and if it got removed from the spec, most developers probably wouldn’t even notice.


And today, even after writing a whole tutorial on it, and reading the entire specification on that subject, I still can’t code a box with a border image without consulting a reference and pulling my hair out.


CSS Counters


Seriously? Does CSS still have these? Another one that I wrote about, hoping to learn it better myself, and hoping to promote its use. But I’ve never used it on any project, and I bet I never will.


The code is so convoluted and unintuitive, that it leaves us scratching our head wondering “Isn’t this what the <ol> element is for??”


CSS Comments


Remind me again, why I can’t do a simple single-line comment using a double forward slash? I’m sure it has something to do with the way forward slashes are parsed. But it would be so much easier if we could comment and uncomment a single line the same way we can in JavaScript, using a double slash at the start of the line.


Double-Colon for Pseudo-Elements


To differentiate between pseudo-elements and pseudo-classes, in CSS3 all pseudo-elements have a double-colon syntax. So instead of: :before, you do ::before.


As I’ve explained before, this is nonsense. All browsers are going to support the single-colon syntax, pretty much indefinitely, to abide by good design principles.


So that means we won’t be using the double-colon syntax until all browsers that don’t support it (including IE8, the current browser leader) are completely gone — which might not be for at least 2 or 3 years, and probably more.


What Else?


Whew. I’m glad I was able to get all this off my chest. You’ll notice that this list has nothing to do with browser inconsistencies (well, except the vendor prefix part), but is more focused on legitimate features of the language.


So feel free to offer your own CSS pet peeves, and things you find about CSS that are not very intuitive or easy to understand. And please — we already know that everyone hates Internet Explorer and all of it’s bugs, so let’s keep this focused on actual features of the language, and not vendor implementations of it.











Source : http://www.impressivewebs.com/css-the-bad-parts

Understanding em Units in CSS




Understanding em Units in CSSDue to developers’ habitual reliance on pixel values, I think some of us may not have a full understanding of what the em unit is, and how it works in CSS.


As is the case with many topics I write about, I’ll probably learn a thing or two while writing this. So I hope this will serve as a nice summary of what em units are all about and how you can use them in your designs.


Ah-em — Definition Please


The spec gives us a very simple definition for the em unit:



Equal to the computed value of the ‘font-size’ property of the element on which it is used.



In other words, if you have the following CSS:



.element {
font-size: 20px;
}

Then this means 1em defined on that element, or any of its children, would be equal to 20px. Here’s proof.


So if you did this:



.element {
font-size: 20px;
width: 4em;
height: 4em;
}

Then that means that the width and height of the element (defined here as 4em x 4em) would compute to 80px x 80px (20px * 4 = 80px).


Let’s em-phasize This


The key to remembering this is based on what an actual “em” unit is, and where it comes from. According to Wikipedia’s article on em:



An em is a unit of measurement in the field of typography, equal to the currently specified point size. The name of em is related to M. Originally the unit was derived from the width of the capital “M” in the given typeface.



The article goes on to explain that although the em unit was originally based on the width of the letter “M”, this is no longer the case, and now the em unit generally refers to the point size of the font.


With this method of calculation, in a CSS file there is no strict definition for what an ‘em’ is; it all depends on what else is going on in your stylesheet. So theoretically, if you’ve declared a whole slew of length values using ems on various elements on your page, changing a single font size has the potential to throw your whole layout off.


What if “font-size” Isn’t em-ployed?


In the example above, and the JSBin I linked to, I’m explicitly defining a font-size. The em unit is subsequently derived from that ‘base’ setting. But what if the element doesn’t have a specified font size?


In that case, since the font-size property inherits through the document tree, the em unit’s value will be derived from whatever is actually inherited. If no font size is specified anywhere in the document, then the value of a single em unit will be equal to 16px, which is the default (and I believe that works the same in all browsers).


“rem” Should Be Automatic for the People


This is a good time to bring up CSS3′s new addition: the rem unit. The rem unit (or “root em” unit) has pretty good browser support: IE9+, FF3.6+, Chrome, Safari 5+, and Opera 11.6+.


From what I can see, the rem unit is pretty straightforward. It lets you base your em units on a ‘root’ unit defined on the <html> element. This way, you could go nuts with font-size settings in all sorts of places in your stylesheet, but any ‘ems’ you define would always be based on the root em unit from your root element (the <html> element).


And as is the case with em, if you don’t define a font-size value on the <html> element, then the root em unit will be the default 16px.


Carpe di-em


Sick of the puns yet? Well, too bad. :)


Having worked in the web design and development field for about 12 years now, it’s taken me a while to break free from fixed-width, pixel-based designs. Although I’ve started doing responsive layouts, I’m still hooked on pixel units. While this might be fine for layout elements, I think for typography, the em unit should be the go-to unit.


While it is possible to do an entire layout with just em units, I think for responsive layouts it’s probably best to use pixels or percentages — and, as mentioned, use ems for typography.


So if you’re like me, let’s seize the day — and start using the super intuitive ems and rems wherever it’s practical and sensible.


If You Can’t Beat em — Join em


Oh and if anyone comments on this article, you have to include an ‘em’ pun. :)











Source : http://www.impressivewebs.com/understanding-em-units-css

Screencast: Why HSL Colors are Awesome




Some of you might know that I did a screencast series for Learnable.com that served as a companion piece to the book of the same name that I co-authored.


In that video series, I covered a number of the new CSS3 and HTML5 features, and one in particular that I haven’t written much about on this site is HSL (or HSLA) colors.


Below you’ll find the video originally titled “HSLA Colors”. In the Learnable series, this video is Step 2 of Lesson 7. Enjoy.



Viewing tip: Click the “change quality” icon (next to the “CC” icon) to select “720p HD” quality, and then use full screen. I can’t figure out how to embed YouTube videos in HD.


If something’s wrong with the embed above, here’s a direct YouTube link:


http://www.youtube.com/watch?v=A60HjujkzhI


Some related links:












Source : http://www.impressivewebs.com/screencast-css3-hsl-colors

CSS3 Attribute Selectors: Substring Matching




CSS3 Attribute Selectors: Substring MatchingThree of the attribute selectors in the CSS3 spec allow you to check the value the specified attribute for a string match. These attribute selectors are referred to as substring matching attribute selectors.


These can open endless possibilities, so I think it’s useful to have them in mind. And as a bonus, these selectors have strong support as far back as IE7, so pending thorough tests I think they are quite safe to use in many current projects.


Here’s a brief outline of each one, with some examples.


“Begins With” Attribute Selector


The first of these three attribute selectors lets you target an element in your CSS based on whether the attribute’s value begins with a given string. Here it is:



a[href^="http://"] {
color: green;
}

This one uses the caret (^) character to tell the browser: “If this link has an href attribute that starts with http://, make it green.” Now, this specific example looks like an easy way to target external links.


But be careful, because if your CMS is adding your site’s URL to the beginning of certain links (like WordPress does), or if you’ve built your site with a “path” variable prepended to all links, then this would target all links that begin with “http://”, regardless of whether they are external or not. So this example might work only in specific circumstances.


To combat this, you might try:



a[href^="http://"] {
color: green;
}

a[href^="http://www.domain.com"], a[href^="http://domain.com"] {
color: blue;
}

But even this is not perfect, because it doesn’t target “https”. So testing is crucial. Nonetheless, this clearly illustrates what this attribute selector does, so you can use it where you think it fits.


Another important note: Don’t confuse this one with what’s been commonly referred to as the “language” attribute selector, which uses the vertical pipe character (|). That attribute selector will only match the specified string if it is at the start of the value and if it precedes a hyphen. This one is commonly used for matching values in the hreflang attribute on links.


“Ends With” Attribute Selector


This next one is exactly the opposite: You can target an element based on the ending of an attribute value. Here it is:



a[href$=".pdf"] {
background: url(../images/pdf.png) no-repeat center right;
padding-right: 20px;
}

This selector uses the dollar sign ($). Now we have what looks like a fairly reliable matching process. We know that all anchor elements that point to PDF documents are going to have the extension “.pdf”, so with this code we can add some right padding to those links and add a PDF icon to the link’s background.


“Contains” Attribute Selector


Finally, this selector targets elements based on any string match within an attribute value. So the specified string could occur anywhere in the value, not just at the beginning or the end.



div[class*="post-"] p {
color: green;
}

The asterisk character (*) is well-known in computing as a wildcard character, so this one’s easy to remember.


The example I’m using may remind you of how WordPress sites attach a number of classes to specific elements, often with prefixes like “post-”. This might not be extremely practical, because usually there is another primary class with which to target the element. But again, it illustrates what can be done, and the type of values you’d be targeting with the wildcard character.


Got Any Use Cases?


Depending on how you build your app, your markup, and how you define certain attributes, the sky is really the limit with these selectors. I’d be glad to hear of any practical ways anyone has used these in their projects.











Source : http://www.impressivewebs.com/css3-attribute-selectors-substring-matching

Book Giveaway: HTML5 & CSS3 for the Real World





This contest is now closed. Congratulations to
Mark Cohen for winning the hard copy, and
Nick Stevens for winning the E-Pack.

A New Book on HTML5 and CSS3This week I’m swamped with stuff outside of this blog, so I thought it would be a good time for another book giveaway. This time I have two copies of HTML5 & CSS3 for the Real World, published by SitePoint.


As many of you know, this is a book that I helped co-author with Estelle Weyl and Alexis Goldstein. You can read a full description along with table of contents on the SitePoint page linked above.


Here’s a brief description of the book:


“HTML5 & CSS3 for the Real World will show you how to create dynamic websites using these new technologies. No fluff or hype here – only fun, effective techniques you can start using today. This easy-to-follow guide covers everything you need to know to get started today. You’ll master the new semantic markup available in HTML5, as well as how to use CSS3 without sacrificing clean markup or resorting to complex workarounds.”


And here are the rules for the contest:


1. Tweet a Link to This Post


Yeah, I know, you don’t want to share this post, because that means you’ll have a lower chance of winning. But you know how it goes, it’s free advertising for me, and it makes the contest all the more exciting! :)


The tweet must contain the following text:


Book Giveaway: HTML5 & CSS3 for the Real World (via @ImpressiveWebs)


Plus a link to this post. A short link is fine, as long as the link goes here.


2. Post a Comment With a Link to Your Tweet


Naturally, you have to prove that you tweeted the article. So you need to find a direct link to your tweet and post it here in the comments. I’ll be sure to check the spam comments so nothing gets filtered out.


Keep in mind that the link to your tweet cannot just be a link to your Twitter account, it must be a link to the individual tweet. In the last giveaway, a few people didn’t get this right. So make sure. On Twitter.com, an individual tweet is found by clicking “open” then “details”. It looks like this.


Only one entry allowed per person.


3. Use a Valid Email Address in Your Comment


If you don’t use a valid email address, then I can’t contact you. So make sure your email address is correct so I can contact you if you win.


Hard Copy and E-Pack Versions


As mentioned, I have two copies of the book to give away. One is a hard copy that I will mail anywhere in the world, using cheap shipping. And the other is an E-Pack version, which includes PDF, MOBI, and EPUB versions of the book.


If the winner of the hardcopy would prefer an E-Pack version, then I’ll ask the winner of the E-Pack if they want to swap. If not, then I’ll gladly give away an extra E-Pack to the winner of the hard copy. So I may give away three copies, it just depends on what the winners prefer.


Two Weeks’ Notice


I’ll give the post two weeks to collect entrants, then I’ll pick two comments at random using a random number generator. The first one I pick will win the hard copy.


From time to time, I will do other book giveaways for quality design and development titles, so be sure to subscribe to one of my feeds to know when these contests are posted:












Source : http://www.impressivewebs.com/book-giveaway-html5-css3

Pure CSS Tool Tips Revisited




Pure CSS Tool Tips RevisitedCreating tool tips with pure CSS and no images or JavaScript is nothing new. I’ve never personally written anything on the topic, but there are plenty of examples and tutorials to choose from.


For a recent project, I had to research the concept and find something that suited my needs. I didn’t spend too many hours researching but, from what I could see, most (if not all) solutions available were satisfactory for most cases, but had a few minor flaws.


So in this post I’ll address these minor weaknesses and present what I think might be a more bulletproof solution.


Fixing Problems With CSS Tool Tips


I think all CSS tool tips should have the following features:



  • No extra HTML

  • Avoid using the “title” attribute

  • Vertical and horizontal fluidity

  • Shouldn’t break when a link spans two lines

  • Shouldn’t use percentages for positioning


Let’s summarizes why these points are important.


Avoiding Extra Markup
Many of the pure CSS solutions utilize an extra <span> element that is initially hidden. This is not necessary and, in my mind, is an obsolete method (even though technically it works in more browsers). Having the extra text in the HTML that way would (I assume) have accessibility problems. So instead we can use a pseudo-element that grabs the value of an attribute on the element being hovered over (more on this below).


Avoiding the “title” Attribute
The next point is about the “title” attribute. Now, if you want a completely cross-browser tooltip, your best bet is to just use a plain old title attribute on the link element, and forget about anything custom. But if you use a custom method, and you’re grabbing a value from an attribute, then you don’t want to use the title attribute. This will cause the tooltip to appear in two different places. Not a huge problem, but I think it’s redundant and sloppy looking.


Use a data- Attribute
So instead of using the title attribute, the best option is HTML5 data attributes (John Resig has a good post on the subject). In short, this is a custom attribute that you create that starts with “data-”. So something like “data-tooltip” is fine, but you can call it whatever you want, as long as it begins with “data-”.


Avoid Breakages
Because pretty much all tool tips are positioned absolutely, this can cause problems if the tooltip is not positioned in a bulletproof manner. So although it might be nicer looking when the tooltip appears in the middle or at the end of the element it’s referencing, a better solution is to make the tooltip appear near the top left corner of the link. This ensures that the tooltip doesn’t appear in the wrong place (for example, when the link spans two lines). To avoid this problem, some have used white-space: nowrap on the links, but I don’t think that’s good, especially if you have links that are longer than one or two words.


Avoid Percentage Units
Another thing I’ve noticed with a lot of tooltip solutions is that they rely on percentages to position the tooltip. This seems like a good way to do it because sometimes you don’t know the size of the element that the tooltip references. But I think it’s best to use pixel values for this, and you’ll see this in the example below.


A Near Bulletproof Solution?


I have no idea if this solution is bulletproof. Maybe there are problems that I haven’t thought of, but after reviewing the bugs in the other solutions, here’s what I’ve come up with:



And here’s the code:



a[data-tooltip]:link, a[data-tooltip]:visited {
position: relative;
text-decoration: none;
border-bottom: solid 1px;
}

a[data-tooltip]:before {
content: "";
position: absolute;
border-top: 20px solid #0090ff;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
visibility: hidden;
top: -18px;
left: -26px;
}

a[data-tooltip]:after {
content: attr(data-tooltip);
position: absolute;
color: white;
top: -35px;
left: -26px;
background: #0090ff;
padding: 5px 15px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
white-space: nowrap;
visibility: hidden;
}

a[data-tooltip]:hover:before, a[data-tooltip]:hover:after {
visibility: visible;
-moz-transition: visibility 0s linear .3s;
}

Here are some notes on the code:



  • I’m using the attribute selector to target only links that have a data-tooltip attribute

  • The text shown for the tooltip is whatever value the data-tooltip attribute has

  • I’m using border-bottom for link underling because text-decoration adds underlining to the tooltip, too

  • Works in IE8+ and everywhere else, as far as I can see

  • Only Firefox animates pseudo-elements, so there is a small delay using transitions on FF, which I think is nicer

  • The tooltip is created using a CSS pure triangle shape and a rounded-corner box (IE8 degrades to square corners)

  • I’m using visibility: hidden, but you could also use display: none; I’m not sure which is better

  • The tooltip is positioned relative to the top left corner of the element, keeping it from breaking when the link spans two lines; the top left corner is always constant

  • The tooltip is positioned using pixels, which, in this case I think is more bulletproof than percentages

  • If you decide to take the code and modify the shape of the tooltip, you might have to alter the positioning of the tooltip


Feedback?


If this can be improved in any way, I’m all ears. I’m also aware that other solutions may have other benefits I haven’t thought of. So if you notice anything I’m overlooking, I’d love to make this a more complete discussion of pros and cons for pure CSS tooltips. I’ll do my best to make any necessary improvements.


If you want to mess around with the code, here’s a JSBin.












Source : http://www.impressivewebs.com/pure-css-tool-tips