Tips to Write Better CSS Code


Tips to write better CSS code
CSS is a language that is not difficult to master, but if you use it for a large project, it can be very difficult to manage if you do not follow a defined approach while writing CSS code. Here are few tips that will help you write better and easy to manage CSS code.
1. Don’t Use Global Reset

Using global reset to remove default margin and padding from all HTML elements is a strict no-no. Not only it is slow and inefficient way but you’ll have to define margin and padding for each element that needs it. Instead use subset of CSS Resets like one from Eric Meyer.
Not Good

*{ margin:0; padding:0; }

Better

html, body, div, dl, dt, dd, ul, h1, h2, h3, pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 }
table { border-collapse:collapse; border-spacing:0 }
fieldset, img { border:0 }
ul { list-style:none }

2. Do not use IE Hacks

Though CSS hacks might be useful to maintain consistent look of the website over older browsers like IE6, but they can be problematic for newer versions of IE as newer versions like IE8 do support CSS standards to a good level and using hacks might break out the layout. You should use conditional statements instead to target specific versions of Internet Explorer.
For example, using the below lines of code within your tag will load the iestyles.css file only when browser is Internet Explorer version 6 or less.



For information on conditional comments, refer to the quirksmode article on CSS Conditional Comments
3. Use Meaningful names for IDs and Classes

Suppose you define your sidebar styles using class .leftbox and after some redesign, you float it to right, then would it be meaningful to have leftbox as name for right floated box. You should put some thought before declaring classes and IDs for elements so that they are meaningful and easy to understand later.
4. Utilize CSS Inheritance

If multiple child elements of a parent element use same styles on your web page, it will be better to define them for their parent element and let the CSS inheritance do all the work. You’ll be able to easily update your code later and it’ll also reduce the CSS file size considerably.
Not Good

#container li{ font-family:Georgia, serif; }
#container p{ font-family:Georgia, serif; }
#container h1{font-family:Georgia, serif; }

Better

#container{ font-family:Georgia, serif; }

5. Combine multiple Selectors

You can combine multiple CSS selectors into one if they have common style definitions. It’ll save you time and space.

Not Good

h1{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h2{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }

Better

h1, h2, h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }

6. Use Shorthand Properties

Utilize the shorthand properties of CSS to quickly write CSS code and reduce file size. Shorthand notation can be used for margin, padding, border, font, background and also for color values.
Not Good

li{
font-family:Arial, Helvetica, sans-serif;
font-size: 1.2em;
line-height: 1.4em;
padding-top:5px;
padding-bottom:10px;
padding-left:5px;
}

Better

li{
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
padding:5px 0 10px 5px;
}

Here’s a complete guide to CSS shorthand properties.
7. Organize CSS Code

Organizing your CSS code in a certain pattern will make it easier to find things at later time and save you a lot of time looking for a specific style definition.
Here is a sample organization that you may use:

/*-------------------------
CSS Reset
-------------------------*/

/*-------------------------
Generic Classes
-------------------------*/

/*-------------------------
Layout styles
-------------------------*/

/*-------------------------
Section specific styles
-------------------------*/

8. Make CSS Readable

Writing readable CSS will make it easier to find and update a style declaration later. Either group all styles for a selector in one line or each style in its own line with proper indentation. You can also combine these two techniques together.

/*------------------------
Each Style on new line
---------------------*/
div{
background-color:#3399cc;
color:#666;
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
height:300px;
margin:10px 5px;
padding:5px 0 10px 5px;
width:30%;
z-index:10;
}

/*------------------------
All Styles on one line
---------------------*/
div{ background-color:#3399cc; color:#666; font: 1.2em/1.4em Arial, Helvetica, sans-serif; height:300px; margin:10px 5px; padding:5px 0 10px 5px; width:30%; z-index:10; }

9. Add proper Comments

Comments can be used to separate different sections of CSS code

/*--------------------
Header
-----------------*/
#header{ height:145px; position:relative; }
#header h1{ width:324px; margin:45px 0 0 20px; float:left; height:72px;}

/*--------------------
Content
-----------------*/
#content{ background:#fff; width:650px; float:left; min-height:600px; overflow:hidden;}
#content .posts{ overflow:hidden; }
#content .recent{ margin-bottom:20px; border-bottom:1px solid #f3f3f3; position:relative; overflow:hidden; }

/*--------------------
Footer
-----------------*/
#footer{ clear:both; padding:50px 5px 0; overflow:hidden;}
#footer h4{ color:#b99d7f; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; }

10. Order CSS Properties Alphabetically
This might be a difficult way to write CSS but it’ll make it easier for you to find out any property easily at a later stage.

div{
background-color:#3399cc;
color: #666;
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
height: 300px;
margin: 10px 5px;
padding:5px 0 10px 5px;
width: 30%;
z-index:10;
}

11. Use External Stylesheets

It is always a good design practice to separate content from presentation. Place all of your CSS code into external stylesheets and use the to reference stylesheets within a web page. By placing CSS into external files, you can easily update your styles later at one place instead of looking into html templates or files for styles.
Not Good



OR



  • Better



    12. Split CSS into multiple files

    If you are working on a large web project that has multiple modules, each with different set of styles and looks, it will be better to split your CSS files into multiple files based on the module they are applied to. You can separate stylesheets like, one for reset, one for layout, one for generic classes and one for module specific styles. This technique will let you organize your code easily in a large project but loading multiple CSS files means more HTTP requests and slower loading time, this is where Bridging CSS files come to rescue. Create a separate CSS file and import other CSS files into it.

    @import "style/css/reset.css";
    @import "style/css/typography.css";
    @import "style/css/layout.css";

    13. Compress CSS code

    Once you are ready to deploy the web design project, compress your CSS code using tools like CSS Compressor to reduce file size and improve loading time of webpage.
    14. Be Consistent in Writing CSS

    When you work on multiple web development projects, it’ll be a wise decision to choose a particular way of organizing and formatting your CSS code and stick to that way for all your projects.

    I hope these tips will help you write better and manageable CSS code. If you would like to share a tip or two, feel free to add your comment below.
  • Quick & Easy Way to Implement Drag n Share With jQuery

    Drag to Share with jQuery
    You must have seen the drag to share functionality on Mashable that lets visitors share the content on popular social networks intuitively. Just drag one of the images in an article and you’ll be able to share the article on your favorite social network by dropping the dragged image over its icon. Even, Nettuts has written a nice tutorial on how to implement this functionality into your website using jQuery. But here is a much elegant solution to achieve the drag n share effect using jQuery with just a line or two of JavaScript code.

    Get the prettySociable Plugin

    To implement this functionality, you will need the prettySociable jQuery plugin written by Stéphane Caron. Download and extract the plugin, it contains everything you need to get up and running with drag n share.

    Include the Required Files

    To add drag n share to a page, add reference to jquery and prettySociable in your page’s head tag. The plugin folder also includes images and css folders in addition to js folder. You’ll need them too as css folder contains styles necessary for drag n share elements and images folder contains icons for various social networks.
    Here’s the complete code you need to add into the head tag.
    
    
    
    
    The js folder also includes DD_belatedPNG.js which is used to fix PNG transparency issues in IE6 or older. You need to include that too.

    Define Draggable Links

    Now to add drag n share to your web page, add an anchor tag with another attribute rel="prettySociable".

    Initialize prettySociable

    After you have added the rel attribute, you need to initialize the script. Add this single line of code, just above the
    
    
    Check out your page in browser and you should get drag to share functionality working nicely.

    Customizing the Default Settings

    Customizing the Shared Information

    When you add rel="prettySociable" on an anchor tag with its href="#", this will share the URL of the current web page and use the title and meta description in head tag to display the tooltip on drag.
    But if you need to share a different URL instead of the current web page, specify a URL in the href attribute. Also you can customize the tooltip information which is shown on dragging. You can specify custom title and description in the rel attribute in this way.
    rel="prettySociable;title:custom title;excerpt:custom excerpt;"

    Customizing the Sharing Panel

    By default prettySociable supports eight social networks but you can customize the social networks and their icons to your requirement. For that you’ll need to pass a settings object to prettySociable function.
    Here’s the complete settings object
    $.prettySociable({
    				animationSpeed: 'fast', /* fast/slow/normal */
    				opacity: 0.90, /* Value between 0 and 1 */
    				share_label: 'Drag to share', /* Text displayed when a user rollover an item */
    				share_on_label: 'Share on ', /* Text displayed when a user rollover a website to share */
    				hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettySociable */
    				hover_padding: 0,
    				websites: {
    					facebook : {
    						'active': true,
    						'encode':true, // If sharing is not working, try to turn to false
    						'title': 'Facebook',
    						'url': 'http://www.facebook.com/share.php?u=',
    						'icon':'images/prettySociable/large_icons/facebook.png',
    						'sizes':{'width':70,'height':70}
    					},
    					twitter : {
    						'active': true,
    						'encode':true, // If sharing is not working, try to turn to false
    						'title': 'Twitter',
    						'url': 'http://twitter.com/home?status=',
    						'icon':'images/prettySociable/large_icons/twitter.png',
    						'sizes':{'width':70,'height':70}
    					},
    					delicious : {
    						'active': true,
    						'encode':true, // If sharing is not working, try to turn to false
    						'title': 'Delicious',
    						'url': 'http://del.icio.us/post?url=',
    						'icon':'images/prettySociable/large_icons/delicious.png',
    						'sizes':{'width':70,'height':70}
    					},
    					digg : {
    						'active': true,
    						'encode':true, // If sharing is not working, try to turn to false
    						'title': 'Digg',
    						'url': 'http://digg.com/submit?phase=2&url=',
    						'icon':'images/prettySociable/large_icons/digg.png',
    						'sizes':{'width':70,'height':70}
    					}
    					//add more social networks here
    				},
    				tooltip: {
    						offsetTop:0,
    						offsetLeft: 10
    					},
    				popup: {
    					width: 900,
    					height: 500
    				},
    				callback: function(){} /* Called when prettySociable is closed */
    			});
    The settings object is self explaining. You can specify which websites to use and also the icons to use for each website in the websites parameter.
    You can enhance this drag n share script even further by using a shortened URL in the anchor tag’s href attribute.
    View Demo or Download prettySociable jQuery plugin.
    P.S.: To get this script to work correctly in IE, you will need to set margin and padding values in the style-sheet for anchor elements which are draggable.

    40 Fresh & Beautiful Examples of Websites With Large Backgrounds

    Using large sized pictures or illustrations as your website’s background adds a great visual appeal to your website’s design. Many web designers use large images as backgrounds as more and more users are now opting for high resolution monitors and high speed internet connections. Here’s a showcase of 40 Fresh and amazing websites that are using large background images.

    1. The Pixel Blog

    The Pixel Blog

    2. Copimaj Interactive

    Copimaj Interactive

    3. Flourish Web Design

    Flourish Web Design

    4. Abduction Lamp

    Abduction Lamp

    5. Morphix Design Studio

    Morphix Design Studio

    6. Final Phase

    Final Phase

    7. Make Photoshop Faster

    Make Photoshop Faster

    8. WebSarga

    Web Sarga

    9. Suie Paparude

    Suie Paparude

    10. Duirwaigh Studios

    Duirwaigh Studios

    11. BlackMoon Design

    BlackMoon Design

    12. Sepitra

    Sepitra

    13. Le Blog de Gruny

    Le Blog de Gruny

    14. Piipe

    Piipe

    15. Mozi Design Studio

    Mozi Design Studio

    16. Electric Current

    Electric Current

    17. Lora Bay Golf

    Lora Bay Golf

    18. Life Style Sports

    LifeStyle Sports

    19. ligne triez

    ligne triez

    20. Oliver Kavanagh

    Oliver Kavanagh

    21. World of Merix Studio

    Merix Studio

    22. Le Web Defi

    le-web-defi

    23. How host

    How host

    24. Productive Dreams

    Productive Dreams

    25. Gary Birnie

    Gary Birnie

    26. Glocal Ventures

    Glocal Ventures

    27. GDR UK

    GDR UK

    28. Absolute Bica

    Absolute Bica

    29. Le Nordik

    Le Nordik

    30. Leaf Tea Shop & Bar

    Leaf Tea Shop

    31. Paul Smith

    Paul Smith

    32. EwingCole

    EwingCole

    33. Dolphins Communication Design

    Dolphins Design

    34. Danny Diablo

    Danny Diablo

    35. Inner Metro Green

    Inner Metro Green

    36. Matt Salik

    Matt Salik

    37. Revyer

    Revyer

    38. Yodaa

    Yodaa

    39. Dripping in Sunshine

    Dripping in Sunshine

    40. Big Break ‘09

    Big Break '09

    JavaScript Execution and Browser Limits

    The browser UI and JavaScript code (effectively*) share a single processing thread. It doesn't matter whether the browser needs to respond to its own menu click, render an HTML page or execute your Ajax call -- every event is added to a single queue. When the browser becomes idle, the next item on it's to-do list is retrieved and executed.
    *In reality, no modern browser operates on a single thread. As an extreme example, IE9 and Chrome start a new OS process for every tab. However, there is still a single event queue per viewed page and only one task can be completed at a time. This is absolutely necessary because the browser or your JavaScript can alter the rendered HTML before, during or after it's downloaded.
    Understandably, the browser must limit the time it takes for your JavaScript code to run. If a script takes too long, it will lock the application and potentially cause OS instability. It's the reason you'll see the dreaded "Unresponsive Script" alert.
    But how does a browser determine when a script has run for too long? As you'd expect, the top 5 vendors implement different techniques and limits…
    Internet Explorer
    IE limits JavaScript execution to 5 million statements.
    Firefox
    Firefox uses a timed limit of 10 seconds.
    Safari
    Safari uses a timed limit of 5 seconds.
    Chrome
    Chrome does not limit execution but detects when the browser crashes or becomes unresponsive.
    Opera
    Opera does not implement a limit and will execute JavaScript indefinitely. However, the browser will not cause system instability -- you can continue to open other tabs or close the page executing the code.
    Several of the browsers allow you to configure the execution limit parameters, but that's not something I'd recommend. I won't publish the details here because someone, somewhere will use it as a "fix" for their unresponsive page! Google it if you like, but tweaking browser settings for badly-behaved code does not address the root of the problem.
    So how can we prevent JavaScript execution alerts? The best solution is to avoid long-running client-side tasks. Ideally, no event handler should take longer than a few dozen milliseconds. Intensive processing jobs should normally be handled by the server and retrieved with a page refresh or an Ajax call.
    However, I'm conscious that minimizing client-side processing is not necessarily a viable solution for today's JavaScript-heavy applications. Fortunately, there are a number of solutions … stay tuned to SitePoint for several alternatives coming soon.
    You can leave a comment on the blog entry: