Friday 4 November 2011

25 usefull css trick

1. Change Text Highlight Color

You might not have known this before! With CSS you can control the colors of selected test at least for standards compliant cutting edge browsers like Safari or Firefox.
  1. ::selection{ /* Safari and Opera */  
  2.     background:#c3effd;  
  3.     color:#000;  
  4. }  
  5. ::-moz-selection{ /* Firefox */  
  6.     background:#c3effd;  
  7.     color:#000;  
  8. }  

2. Prevent Firefox Scrollbar Jump

Firefox usually hides the vertical scrollbar if size of the content is less than the visible window but you can fix that using this simple CSS trick.
  1. html{ overflow-y:scroll; }  

3. Print Page Breaks

While most of the internet users prefer to read content online but some of your users might like to print your article. With CSS you can control the page breaks within content just add this CSS class to your stylesheet and add this class to any tag which you would like to print on next page.
  1. .page-break{ page-break-before:always; }  

4. Using !important

Experienced CSS programmers are usually aware of this but beginners do miss out on this !important CSS rule. By adding !important to your CSS rule, you can increase its precedence over other subsequent rules. e.g. in below code, background-color will be blue and not red due to !important.
  1. .page { background-color:blue !important;   background-color:red;}  

5. Replace Text With Image

This is a nice SEO trick that lets you show a nice fancy image instead of simple boring text to your visitors but search engines will see only the text.
  1. .header{  
  2.     text-indent:-9999px;  
  3.     background:url('someimage.jpg'no-repeat;  
  4.     height100px/*dimensions equal to image size*/  
  5.     width:500px;  
  6. }  

6. Cross Browser Minimum Height

Internet Explorer does not understand the min-height property but here’s the CSS trick to accomplish that in IE.
  1. #container{  
  2.     height:auto !important;/*all browsers except ie6 will respect the !important flag*/  
  3.     min-height:500px;  
  4.     height:500px;/*Should have the same value as the min height above*/  
  5. }  

7. Highlight links that open in a new window

This piece of CSS code will highlight links that open in a new window so that user knows before hand that link will pop open in a new tab or window.
  1. a[target="_blank"]:before,  
  2. a[target="new"]:before {  
  3.     margin:0 5px 0 0;  
  4.     padding:1px;  
  5.     outline:1px solid #333;  
  6.     color:#333;  
  7.     background:#ff9;  
  8.     font:12px "Zapf Dingbats";  
  9.     content"\279C";  
  10. }  

8. Style Your Ordered List

Style Ordered List
Style numbers of an ordered list in different way than the content of each list item.

  1. ol {  
  2.     fontitalic 1em Georgia, Times, serif;  
  3.     color#999999;  
  4. }  
  5. ol p {  
  6.     fontnormal .8em ArialHelveticasans-serif;  
  7.     color#000000;  
  8. }  

9. Drop Caps Using CSS

Drop Caps using CSS
You can create a drop caps effect like those in newspapers or magazines using the :first-letter pseudo element.
  1. p:first-letter{  
  2. display:block;  
  3. margin:5px 0 0 5px;  
  4. float:left;  
  5. color:#FF3366;  
  6. font-size:3.0em;  
  7. font-family:Georgia;  
  8. }  

10. Cross Browser Opacity

Though CSS3 standard includes the opacity property, but not every browser supports it, here’s the CSS trick for cross browser transparency.
  1. .transparent_class {  
  2.     filter:alpha(opacity=50);  
  3.     -moz-opacity:0.5;  
  4.     -khtml-opacity: 0.5;  
  5.     opacity: 0.5;  
  6. }  

11. Vertical centering with line-height

If you are using fixed height container and need to vertically center the text, use the line-height property to do that perfectly.
  1. line-height:30px;  

12. Center Fixed Width layout

If you use fixed width layout, you should center the layout so that if somebody views it on larger screen, the page displays in the center of the screen and not on left side.
  1. body{  
  2.     width:1000px;  
  3.     margin:0 auto;  
  4. }  

13. Remove vertical textarea scrollbar in IE

IE adds a vertical scrollbar to textarea input fields regardless of the height of content in it. You can fix that with this simple CSS trick.
  1. textarea{  
  2.     overflow:auto;  
  3. }  

14. Remove active link borders

Some browsers like Firefox and IE add a dotted outline border over the link user clicked. It is a useful accessibility feature that lets user know which link he clicked or is in focus. But sometimes you need to get rid of this, here’s the CSS you need to use.
  1. a:active, a:focus{ outline:none; }  

15. Prevent Elements from disappearing in IE

Sometimes IE behaves in a peculiar way and makes some elements disappear, which appear when you try to make a selection. It is due to some IE issues with float elements. This can be fixed by adding position:relative; to elements that disappears.

16. Attribute-Specific Icons

CSS Attribute selectors are very powerful giving you many options to control styles of different elements e.g. you can add an icon based on the href attribute of the a tag to let the user know whether link points to an image, pdf, doc file etc.
  1. a[href$='.doc'] {  
  2.     padding:0 20px 0 0;  
  3.     background:transparent url(/graphics/icons/doc.gif) no-repeat center rightright;  
  4. }  

17. CSS Pointer Cursors

This trend has caught up lately. All user interface elements on a web page that can be clicked by user have their cursor similar to that of hyperlink. Here’s the CSS trick to do that.
  1. input[type=submit],label,select,.pointer { cursor:pointer; }  

18. Capitalize Text

This trick is especially useful for displaying title of an article on a web page with all its words starting with capital letter.
  1. text-transformcapitalize;  

19. Small Caps Text

This is one of the lesser used but useful CSS property. It capitalizes all the letters of text but the size of letters following the first letter of each word is smaller than the first letter.
  1. font-variant:small-caps;  

20. Highlight Text Input Fields

This CSS trick lets you highlight the input field currently in focus. This trick does not work in IE though.
  1. input[type=text]:focus, input[type=password]:focus{  
  2.     border:2px solid #000;  
  3. }  

21. Remove Image Border

Image hyperlinks usually get a ugly blue border that makes your image hyperlinks look horrible. It’s better to remove border on all hyperlinked images and add individually to those you want using CSS classes.
  1. a img{ border:none; }  

22. Tableless Forms Using labels

Tableless Forms using labels and CSS
Gone are the days when tables were used to layout Forms. CSS lets you make accessible forms with table like layout using label tags. Using label tags makes sure your forms are more accessible. Here’s sample html and css code for tableless form using labels.
  1. <form method="post" action="#" >  
  2.     <p><label for="username" >Username</label>  
  3.         <input type="text" id="username" name="username" />  
  4.     </p>  
  5.     <p><label for="password" >Username</label>  
  6.         <input type="password" id="password" name="pass" />  
  7.     </p>  
  8.     <p><input type="submit" value="Submit" /></p>  
  9. </form>  
  1. p label{  
  2.     width:100px;  
  3.     float:left;  
  4.     margin-right:10px;  
  5.     text-align:rightright;  
  6. }  

23. Set a Consistent Base Font Size

Setting the font-size property to 62.5% in body tag makes 1em equal to 10px. This lets you use em easily as you can find out the font-size in pixels from em values.
  1. body{ font-size:62.5%; }  

24. Highlight Acronym and Abbr Tags

acronym and abbr tags provide useful information to users, browsers and search engines about acronyms and abbreviations, but most of the browsers except Firefox do not highlight them. Here’s the CSS trick to highlight acronym and abbr tags within your web page.
  1. acronym, abbr{  
  2.     border-bottom:1px dotted #333;  
  3.     cursor:help;  
  4. }  

25. CSS Reset by Eric Meyer

This piece of CSS code resets all the browser default styles preventing any browser inconsistencies in your CSS styles.
  1. html, body, div, span, applet, object, iframe,  
  2. h1, h2, h3, h4, h5, h6, p, blockquote, pre,  
  3. a, abbr, acronym, address, big, cite, code,  
  4. del, dfn, em, font, img, ins, kbd, q, s, samp,  
  5. small, strike, strong, sub, sup, tt, var,  
  6. b, u, i, center,  
  7. dl, dt, dd, ol, ul, li,  
  8. fieldset, form, label, legend,  
  9. table, caption, tbody, tfoot, thead, tr, th, td {  
  10. margin: 0;  
  11. padding: 0;  
  12. border: 0;  
  13. outline: 0;  
  14. font-size: 100%;  
  15. vertical-alignbaselinebaseline;  
  16. backgroundtransparent;  
  17. }  
  18. body {  
  19. line-height: 1;  
  20. }  
  21. ol, ul {  
  22. list-stylenone;  
  23. }  
  24. blockquote, q {  
  25. quotesnone;  
  26. }  
  27. blockquote:before, blockquote:after,  
  28. q:before, q:after {  
  29. content'';  
  30. contentnone;  
  31. }  
  32.   
  33. /* remember to define focus styles! */  
  34. :focus {  
  35. outline: 0;  
  36. }  
  37.   
  38. /* remember to highlight inserts somehow! */  
  39. ins {  
  40. text-decorationnone;  
  41. }  
  42. del {  
  43. text-decorationline-through;  
  44. }  
  45.   
  46. /* tables still need 'cellspacing="0"' in the markup */  
  47. table {  
  48. border-collapsecollapse;  
  49. border-spacing: 0;  

15 Power Full Jquery tips

1) Use the Latest Version of jQuery

With all the innovation taking place in the jQuery project, one of the easiest ways to improve the performance of your web site is to simply use the latest version of jQuery. Every release of the library introduces optimizations and bug fixes, and most of the time upgrading involves only changing a script tag.
You can even include jQuery directly from Google’s servers, which provide free CDN hosting for a number of JavaScript libraries.
1<!-- Include a specific version of jQuery -->
3 
4<!-- Include the latest version in the 1.6 branch -->
The latter example will include the latest 1.6.x version automatically as it becomes available, but as pointed out on css-tricks, it is cached only for an hour, so you better not use it in production environments.

2) Keep Selectors Simple

Up until recently, retrieving DOM elements with jQuery was a finely choreographed combination of parsing selector strings, JavaScript loops and inbuilt APIs like getElementById(), getElementsByTagName() and getElementsByClassName(). But now, all major browsers support querySelectorAll(), which understands CSS query selectors and brings a significant performance gain.
However, you should still try to optimize the way you retrieve elements. Not to mention that a lot of users still use older browsers that force jQuery into traversing the DOM tree, which is slow.
1$('li[data-selected="true"] a') // Fancy, but slow
2$('li.selected a'// Better
3$('#elem'// Best
Selecting by id is the fastest. If you need to select by class name, prefix it with a tag – $('li.selected'). These optimizations mainly affect older browsers and mobile devices.
Accessing the DOM will always be the slowest part of every JavaScript application, so minimizing it is beneficial. One of the ways to do this, is to cache the results that jQuery gives you. The variable you choose will hold a jQuery object, which you can access later in your script.
1var buttons = $('#navigation a.button');
2 
3// Some prefer prefixing their jQuery variables with $:
4var $buttons = $('#navigation a.button');
Another thing worth noting, is that jQuery gives you a large number of additional selectors for convenience, such as :visible, :hidden, :animated and more, which are not valid CSS3 selectors. The result is that if you use them the library cannot utilize querySelectorAll(). To remedy the situation, you can first select the elements you want to work with, and later filter them, like this:
1$('a.button:animated'); // Does not use querySelectorAll()
2$('a.button').filter(':animated');  // Uses it
The results of the above are the same, with the exception that the second example is faster.

3) jQuery Objects as Arrays

The result of running a selector is a jQuery object. However, the library makes it appear as if you are working with an array by defining index elements and a length.
01// Selecting all the navigation buttons:
02var buttons = $('#navigation a.button');
03 
04// We can loop though the collection:
05for(var i=0;i<buttons.length;i++){
06    console.log(buttons[i]);    // A DOM element, not a jQuery object
07}
08 
09// We can even slice it:
10var firstFour = buttons.slice(0,4);
If performance is what you are after, using a simple for (or a while) loop instead of $.each(), can make your code several times faster.
Checking the length is also the only way to determine whether your collection contains any elements.
1if(buttons){    // This is always true
2    // Do something
3}
4 
5if(buttons.length){ // True only if buttons contains elements
6    // Do something
7}

4) The Selector Property

jQuery provides a property which contains the selector that was used to start the chain.
1$('#container li:first-child').selector    // #container li:first-child
2$('#container li').filter(':first-child').selector    // #container li.filter(:first-child)
Although the examples above target the same element, the selectors are quite different. The second one is actually invalid – you can’t use it as the basis of a new jQuery object. It only shows that the filter method was used to narrow down the collection.

5) Create an Empty jQuery Object

Creating a new jQuery object can bring significant overhead. Sometimes, you might need to create an empty object, and fill it in with the add() method later.
1var container = $([]);
2container.add(another_element);
This is also the basis for the quickEach() method that you can use as a faster alternative to the default each().

6) Select a Random Element

As I mentioned above, jQuery adds its own selection filters. As with everything else in the library, you can also create your own. To do this simply add a new function to the $.expr[':'] object. One awesome use case was presented by Waldek Mastykarz on his blog: creating a selector for retrieving a random element. You can see a slightly modified version of his code below:
01(function($){
02    var random = 0;
03 
04    $.expr[':'].random = function(a, i, m, r) {
05        if (i == 0) {
06            random = Math.floor(Math.random() * r.length);
07        }
08        return i == random;
09    };
10 
11})(jQuery);
12 
13// This is how you use it:
14$('li:random').addClass('glow');

7) Use CSS Hooks

The CSS hooks API was introduced to give developers the ability to get and set particular CSS values. Using it, you can hide browser specific implementations and expose a unified interface for accessing particular properties.
01$.cssHooks['borderRadius'] = {
02        get: function(elem, computed, extra){
03            // Depending on the browser, read the value of
04            // -moz-border-radius, -webkit-border-radius or border-radius
05        },
06        set: function(elem, value){
07            // Set the appropriate CSS3 property
08        }
09};
10 
11// Use it without worrying which property the browser actually understands:
12$('#rect').css('borderRadius',5);
What is even better, is that people have already built a rich library of supported CSS hooks that you can use for free in your next project.

8) Use Custom Easing Functions

You have probably heard of the jQuery easing plugin by now – it allows you to add effects to your animations. The only shortcoming is that this is another JavaScript file your visitors have to load. Luckily enough, you can simply copy the effect you need from the plugin file, and add it to the jQuery.easing object:
1$.easing.easeInOutQuad = function (x, t, b, c, d) {
2    if ((t/=d/2) < 1) return c/2*t*t + b;
3    return -c/2 * ((--t)*(t-2) - 1) + b;
4};
5 
6// To use it:
7$('#elem').animate({width:200},'slow','easeInOutQuad');

9) The $.proxy()

One of the drawbacks to using callback functions in jQuery has always been that when they are executed by a method of the library, the context is set to a different element. For example, if you have this markup:
1<div id="panel" style="display:none">
2    <button>Close</button>
3</div>
And you try to execute this code:
1$('#panel').fadeIn(function(){
2    // this points to #panel
3    $('#panel button').click(function(){
4        // this points to the button
5        $(this).fadeOut();
6    });
7});
You will run into a problem – the button will disappear, not the panel. With $.proxy, you can write it like this:
1$('#panel').fadeIn(function(){
2    // Using $.proxy to bind this:
3 
4    $('#panel button').click($.proxy(function(){
5        // this points to #panel
6        $(this).fadeOut();
7    },this));
8});
Which will do what you expect. The $.proxy function takes two arguments – your original function, and a context. It returns a new function in which the value of this is always fixed to the context. You can read more about $.proxy in the docs.

10) Determine the Weight of Your Page

A simple fact: the more content your page has, the more time it takes your browser to render it. You can get a quick count of the number of DOM elements on your page by running this in your console:
1console.log( $('*').length );
The smaller the number, the faster the website is rendered. You can optimize it by removing redundant markup and unnecessary wrapping elements.

11) Turn your Code into a jQuery Plugin

If you invest some time in writing a piece of jQuery code, consider turning it into a plugin. This promotes code reuse, limits dependencies and helps you organize your project’s code base. Most of the tutorials on Tutorialzine are organized as plugins, so that it is easy for people to simply drop them in their sites and use them.
Creating a jQuery plugin couldn’t be easier:
1(function($){
2    $.fn.yourPluginName = function(){
3        // Your code goes here
4        return this;
5    };
6})(jQuery);
Read a detailed tutorial on turning jQuery code into a plugin.

12) Set Global AJAX Defaults

When triggering AJAX requests in your application, you often need to display some kind of indication that a request is in progress. This can be done by displaying a loading animation, or using a dark overlay. Managing this indicator in every single $.get or $.post call can quickly become tedious.
The best solution is to set global AJAX defaults using one of jQuery’s methods.
01// ajaxSetup is useful for setting general defaults:
02$.ajaxSetup({
03    url         : '/ajax/',
04    dataType    : 'json'
05});
06 
07$.ajaxStart(function(){
08    showIndicator();
09    disableButtons();
10});
11 
12$.ajaxComplete(function(){
13    hideIndicator();
14    enableButtons();
15});
16 
17/*
18    // Additional methods you can use:
19    $.ajaxStop();
20    $.ajaxError();
21    $.ajaxSuccess();
22    $.ajaxSend();
23*/
Read the docs about jQuery’s AJAX functionality.

13) Use delay() for Animations

Chaining animation effects is a powerful tool in every jQuery developer’s toolbox. One of the more overlooked features is that you can introduce delays between animations.
1// This is wrong:
2$('#elem').animate({width:200},function(){
3    setTimeout(function(){
4        $('#elem').animate({marginTop:100});
5    },2000);
6});
7 
8// Do it like this:
9$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});
To appreciate how much time jQuery’s animation() save us, just imagine if you had to manage everything yourself: you would need to set timeouts, parse property values, keep track of the animation progress, cancel when appropriate and update numerous variables on every step.
Read the docs about jQuery animations.

14) Make Use of  HTML5 Data Attributes

HTML5 data attributes are a simple means to embed data in a webpage. It is useful for exchanging data between the server and the front end, something that used to require outputting <script> blocks or hidden markup.
With the recent updates to the jQuery data() method, HTML5 data attributes are pulled automatically and are available as entries, as you can see from the example below:
1<div id="d1" data-role="page" data-last-value="43" data-hidden="true"
2    data-options='{"name":"John"}'>
3</div>
To access the data attributes of this div, you would use code like the one below:
1$("#d1").data("role");          // "page"
2$("#d1").data("lastValue");     // 43
3$("#d1").data("hidden");        // true;
4$("#d1").data("options").name;  // "John";
Read more about data() in the jQuery docs.

15) Local Storage and jQuery

Local storage is a dead simple API for storing information on the client side. Simply add your data as a property of the global localStorage object:
1localStorage.someData = "This is going to be saved across page refreshes and browser restarts";
The bad news is that it is not supported in older browsers. This is where you can use one of the many jQuery plugins that provide different fallbacks if localStorage is not available, which makes client-side storage work almost everywhere.
Here is an example using the $.jStorage jQuery plugin:
01// Check if "key" exists in the storage
02var value = $.jStorage.get("key");
03if(!value){
04    // if not - load the data from the server
05    value = load_data_from_server();
06    // and save it
07    $.jStorage.set("key",value);
08}
09 
10// Use value