We see different CSS tips and tricks articles almost in every popular website. However, different articles have their own CSS tips and tricks. This makes me wondering that it will be great to have one single CSS tips and tricks collection. A collection that gather all great tips and tricks that has been found since the beginning popular demand of CSS. Well, this might as well be a selfish article that i would like to have for my own collection. Hence, in this article you might just find all of the great CSS tips and tricks that might satisfy your CSS work demand! (This article does not include techniques)
Tips
Below gathered all the tips that might help you change the way you write CSS.
Avoid Hacks
Try avoiding using hack to solve your problem for IE 6 and below. Sometimes it might not be the problem of compatibility that caused your CSS not working on IE. It might just be the mistake made by you. Furthermore, you can't guarantee that these hack will work forever in the future. It might just come back hunting you in the future. We never know when new browser will have the capability to read those tag right?
Organize CSS definition
It is a good practice to always organize your CSS definition. Depending on how you organize it might just help you in term of usability and maintainability in the future. You can try organizing your CSS definition by block,
/*Header*/ /*Content*/ /*Footer*/ /*Siderbar*/ /*Menu*/
Maintaining this way allows you to easily find the tag whenever you needed a change. On the other hand, you can also arrange it according to type such as
h1{} h1.listitem{} h1#special{} h2{} h2 div{} h2.someitem{} h2#gooditem{}
This way of organization may be good as comment is unnecessary. However, many redundancy might occur. We can also write down references on top of the CSS header to keep us reminded on the choices we made for our CSS definition.
/***References*** * Author: Clay Lua * Created: 01/01/2009 * Last Modified: 18/07/2009 * Theme Name: Wack My Ass Theme * Description: this theme will surprise visitors with a butt kicking color theme * Image used: whatever.jpg, hello.jpg, home.jpg, contact.jpg * Color used: #000, #FFF, #365, #CCC * Font used: Arial, Helvetica, sans-serif; ***************/
Some of us might like it and some of us are just too lazy to deal with it. However, keeping such record might help you track down who was the last culprit that masses up your CSS definition!
Group Similar Selector
This is something that majority of us will know what to do. The concept of grouping similar selector is quite simple. Instead of having so many line of similar definition. We group them up instead. For example,
.example1{#color:#000} .example2{#color:#000} #example3{#color:#000} h2{#color:000}
Writing something like this might just help you increase the time needed to load your stylesheet. Do yourself a favor and group them instead.
.example1,.example2,#example3,h2{#color:#000}
This really can help you cut down some fat bytes if you are practicing the initial declaration. But what if grouping the definition breaks down your organization? We will just have to place these grouping on a special organization block or provide special comment on them. What if a specific element have somewhat more definition than the others but share some similarity? Grouping still should be done and for those outcast, we will just declare them separately such as this,
.example1,.example2,#example3,h2{#color:#000} .h2{font-size:2em}
We are using h2 as an example here that have the following declaration originally.
.h2{font-size:2em;#color:#000;}
Since, everyone share the same color, we can optimize them by grouping the color together to avoid many lines needed for the same color to appear at different location. Hence, reduce the number of line in the CSS file.
Avoid Unnecessary Selector
Like developer program to be efficient by writing less code to achieve something big. Similarly, we want to achieve the same with CSS by writing less definition and at the same time achieve the overall design so that the view can be loaded quickly. There are many times we see CSS definition such as these:
div#unique{color:#000} h2.group{color:#392}
Since id and classes really meant to refer to a specific tag. We can safely remove the type of the tag and achieve the same result with these:
#unique{color:#000} .group{color:#392}
Avoiding unnecessary selector such as the type of the tag can help us reduce some bytes on the stylesheet. Furthermore, we really don't need them! Some of us would like to do this:
#main { width: 530px; padding: 10px; float: left; } #main #nav{ background: #fff; width:100% } #main #left-col { background: #ef; margin: 8px 0; }
for organization purposes having multiple id #main selector to remind us that they are related is a great thing but do we need them when we already organize our definition using comment block? Think about it.
Use meaningful name
Other than organizing our CSS definition in our file. Another important thing is to use meaningful name for each class and id. Having these name makes people understand what does the definition stand for and makes life easier in the future if you ever want to maintain it. Like many developers are taught to use meaningful name for their function/method in a class, same thing apply to CSS. Having a name such as this
#kelly{} #dolly{} #melly{} #merlly{} #molly{}
compare to this
#header{} #footer{} #content{} #siderbar{} #menu{}
do make a difference. (who will have guess header is actually kelly?!)
Alphabetical Properties
Another important thing in declaring your CSS within a definition is the arrangement of each property. Having an alphabetical order properties can really help you scan out the property much easier than arranging it disorderly. Everyone who uses a dictionary will know how useful it is to arrange it this way compare to a dictionary which messes their arrangement up. Luckily, there are a href='http://hungred.com/useful-information/really-useful-web-based-tools-speed-web-development/'>web based tools that can help us do this quickly. Here is an example of an alphabetical order properties:
body { background:#fdfdfd; color:#333; font-size:1em; line-height:1.4; margin:0; padding:0; }
Avoid !important
Some of us love !important when we want to overwrite certain xyz person CSS definition and have no clue or simply lazy to find them out. For conveniences, this is pretty good. However, using too many !important might just destroy your site usability. There are two types of !important. One refers to author and the other refers to the user. Once, author uses !important, it will always prioritize higher than the user one. Hence, any changes made by the user will be invalid. This means any changes such as font size and color will be deem invalid. Hence, usability, fail.
CSS order priority
In order to better improve usability. The only thing we need to understand is CSS order priority. Rather than simply using !important to overwrite others CSS definition. We can avoid them by taking advantage on how CSS prioritize each element. You can easily understand them in CSS priority order tips and tricks
Use CSS ShortHands
If you want to speed up your website. This is something you must learn. It is a good practice to always use CSS shorthands as it helps to optimize your stylesheet. Instead of declaring something like this,
#image{ background-image: url(images/someimage.jpg); background-repeat: no-repeat; background-color: transparent;
we can reduce the above definition by using shorthand such as
#image{background: transparent url(images/someimage.jpg) no-repeat 100% 100%};
Not only property have shorthand in CSS, we can also apply shorthand on colors too!
color: #000000 color: #FFFFFF color: #554422
Each of the above can be written as
color: #000 color: #FFF color: #542
It is actually identical. CSS shorthands is powerful and quite easy to learn.
Avoid Unnecessary length type
Often we see people declaring a type for '0' which is totally unnecessary as it is understood that '0' is universal in term of any given type. Hence,
0em 0% 0px 0in 0cm etc.
is the same as
0
Why not remove the unnecessary type for value 0? This can definitely reduce some byte if in every 0 in your style has included a type.
Case Sensitive
There is a differences between an uppercase compare to a lowercase in CSS. Therefore, we need to understand that every definition name must be identical to the tag written in order for CSS to work properly. Hence, i always use lowercase to make things simplify.
Remove Redundancy
We often forget and tend to write extra or duplicate declaration in order to try an error hoping for it to work and forget to remove those extra property written in our definition. This naturally increase the number of duplication and redundancy in our CSS file. The browser will have to do extra job and the client will have to download the extra bytes. Try removing these duplication with any web based tools or minimize it a long the way.
Avoid Many Absolute Positioning
Some of us love to use absolute positioning as it is easy and get the job done quickly. However, absolute position also means that the element is positioned absolutely at that location even if you minimize the browser? This means that if you absolute position a particular sidebar to the right with a floating element on the left, it will not 'minimize' upon browser minimization. On the other hand, it will move along with the browser during minimization and might caused your layout to break (because it is absolutely required to be positioned at THAT position). Hence, try avoiding using absolute position unless necessary.
Avoid Unnecessary Classes
We often can see something amusing such as this
<ul id='unorder'> <li class='list'></li> <li class='list'></li> <li class='list'></li> <li class='list'></li> <li class='list'></li> </ul>
But it can simplify and remove the class instead to something cleaner and smaller.
<ul id='unorder'> <li></li> <li></li> <li></li> <li></li> <li></li> </ul>
And have a CSS definition such as this
#unorder li{color:#000}
And this is what it means to have unnecessary class. We just do it sometimes Unconsciously.
Use EM for layout
Using EM to layout which is also known as elastic layout design is great for your website. It has both fixed and fluid layout design advantages. This means that your layout will not break whenever user resize their font size. We won't want our design to break whenever user perform such stunt don't we? Smashing magazine writes an excellent article about it!
Validate your code
It is always a good practice to validate your code throughout the development life cycle of your theme. Validating your CSS code will ensure that everything is correct and assure that mistake is not being made by you but the browser instead.
Rationale your code
Similar to validating your CSS code. It is also important to rationale whether the decision made is necessary. Determine whether each definition can be improve by grouping, shorthands, remove redundancy or it can be done without adding that extra wrapper.
Planning and thinking might just what you need before working on any CSS code in order to produce a better and more understandable code.
Reduce div block
We often see many new designers using many div block on their design making it totally difficult to manage. Even tag such as H1,H2,H3,H4,ol,ul,li,strong,em,span are being replaced with div block. There are other tag for a reason! Utilize them! This makes your overall design more readable and understandable. Maintaining it won't be difficult and people will be more appreciative (without scolding you behind your back) towardsthe way you design your website.
Import CSS Style
Another good practice is to a master CSS file to import other CSS files. This way we will only required to write one sentence on the header of the HTML file and leave the rest to the master file. On the other hand, importing your CSS files also help remove compatibility for IE4 (this means we import statement is not support on IE4). Hence, you should write your CSS in this way to avoid IE4 to import your CSS file.
@import "file.css";
centricle has a very nice chart for this.
Use CSS Conditional For IE
Instead of using CSS hack on every browser, we can specific these hacks to a particular IE browser instead by using CSS conditional comments.
<p><!--[if IE]> According to the conditional comment this is Internet Explorer<br /> <![endif]--> <!--[if IE 5]> According to the conditional comment this is Internet Explorer 5<br /> <![endif]--> <!--[if IE 5.0]> According to the conditional comment this is Internet Explorer 5.0<br /> <![endif]--> <!--[if IE 5.5]> According to the conditional comment this is Internet Explorer 5.5<br /> <![endif]--> <!--[if IE 6]> According to the conditional comment this is Internet Explorer 6<br /> <![endif]--> <!--[if IE 7]> According to the conditional comment this is Internet Explorer 7<br /> <![endif]--> <!--[if gte IE 5]> According to the conditional comment this is Internet Explorer 5 and up<br /> <![endif]--> <!--[if lt IE 6]> According to the conditional comment this is Internet Explorer lower than 6<br /> <![endif]--> <!--[if lte IE 5.5]> According to the conditional comment this is Internet Explorer lower or equal to 5.5<br /> <![endif]--> <!--[if gt IE 6]> According to the conditional comment this is Internet Explorer greater than 6<br /> <![endif]--> </p>
Take note that the syntax above gt means greater than whereas lte means less than or equal. Conditional comments is supported only in IE 5 and above. This way, your hack will not affect other browser during execution!
Cater To Different Views
We can provide different views to different devices by stating different media. We can have different CSS file for different media.
<link rel="stylesheet" media="screen,projection,tv" href="main.css" type="text/css"> <link rel="stylesheet" media="print" href="print.css" type="text/css"> <link rel="stylesheet" media="handheld" href="smallscreen.css" type="text/css">
The other way is to use the keyword @media to specific the style of the media.
@media screen, projection, tv { #foo { position: absolute; } } @media print { #navi { display: none; } } @media handheld { #foo { position: static; } }
While the last way, we can use the @import to import the stylesheet for a particular media
@import url(bigscreen.css) screen, projection, tv; @import url(print.css) print; @import url(smallscreen.css) handheld;
However, this is not supported on IE version 7 and above.
Avoid Quote in URL
We can safely avoid any quote required in the url bracket. It is understood that within the bracket it should be a path. Hence, regardless whether there is a quote it will still work. Therefore, we can save some bytes in every situation where it required a url definition such as the one shown below,
@import url(example.css); background: transparent url(css/image.jpg) no-repeat 100% 100%;
Optimize CSS File
After we have completed our CSS styling. The final step is to optimize with file using any web based tools available online. Optimizing CSS file will greatly help reduce those extra bytes by reducing other criteria that we might omitted such as empty spacing, white space or extra closing tag at the end of each definition.
Tricks
Below gathered all the tricks necessary in almost every CSS but difficult to remember for some of us.
Absolute Position Within Container
The trick to absolute position anything within a container is letting the container position relatively!
#container{ position:relative; width: 200px; height: 200px; border: #000 solid 1px; } #inside_element{ position: absolute; left: 0; top: 0; width: 100px; height: 100px; border: #000 dotted 1px; }
#inside_element will position at the far left side of #container although it is position at coordinate (0,0). This is pretty simple. Just try it 🙂
Force Page Break
We will need to force a page break if we are dealing with printing media of our website. Hence, these can be pretty useful if you are catering such media view for your visitors.
h1{ page-break-before:always; } h2{ page-break-after:avoid; } h2{ page-break-inside:always; }
These methods are stated in W3school print properties and W3Org
Text transform
We can perform text transformation on CSS alone. No JavaScript or PHP is required to style our text!
h1 { text-transform:uppercase; } h2 { text-transform:capitalize; } p { text-transform:lowercase; }
PNG Fix in IE
We can fix png problem by using the following code
#myimage{ background:none; float:left; width:150px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='test.png', sizingMethod='scale'); }
Although there are other solution such as using JavaScript. I will prefer a more shorter code approach.
Set Consistence Base Font Size
It is good to use em to size font instead of using px. This can really improve usability as the font will resize when focus. However, calculating EM is a pain in the ass. 1EM is equal to 16px. 1024px is equal to how much EM again? Argh, this is troublesome. We can convert it nicely by converting 1EM to 10px by doing the following.
body { font-size: 62.5% }
This way we can safely assume 1em is 10px and resizing the font won't hard.
p{ font-size: 0.8em; //8px }
Pretty neat stuff.
Prevent Float From Over-float
If you haven't encounter such problem where your float element is floating all over the place and unstoppable! There are actually solution for you to treat these floating element as single block to prevent it to overlapped every element it sees. The solution is to use overflow:auto or hidden on top of the wrapper.
#container{ overflow: auto; } #container_floating_element{ float:left; width: 100px; height: 100px; }
You can read more on the above solution and other solutions at Various Ways To Fix Container Height To Float Element In CSS
Sequence Of Anchor Pseudo-classes
In CSS, the sequences of the anchor pseudo classes is really important for it to work properly.
a:link {color:#FF0000} /* unvisited link */<br /> a:visited {color:#00FF00} /* visited link */<br /> a:hover {color:#FF00FF} /* mouse over link */<br /> a:active {color:#0000FF} /* selected link */<br />
You can read more on the tips of anchor pseudo classes at CSS order priority tips and tricks
Remove vertical scrollbar in IE
We can remove that ugly scrollbar in IE textarea by doing the following CSS definition:
textarea{ overflow: auto }
Just that simple!
Use CSS global reset value
This is every beginner CSS designer mistake. They often did not reset the CSS style before using it. It is important to reset the CSS style as different browser might have different default value. On the other hand, resetting the global value also help to ignore the need to define '0' value for any property. (this means margin: 0 is not needed if we have already reset it globally). Thus, reduce further more byte on the css file. There are many reset value for CSS. However, i will prefer the YUI one. We can either call it this way on our HTML (we don't host that extra file),
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.0r4/build/reset/reset-min.css">
Or you can embed the reset on your own CSS file
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; } table { border-collapse:collapse; border-spacing:0; } fieldset,img { border:0; } address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; } ol,ul { list-style:none; } caption,th { text-align:left; } h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; } q:before,q:after { content:''; } abbr,acronym { border:0; }
I will prefer letting YUI take care of the file since it doesn't hook up my bandwidth for that particular CSS request and it is much faster compare to share hosting.
Cross Browser Align Center
We can easily align center horizontally using margin and display property.
#container{ display:block; width: 200px; height: 50px; margin: 0 auto; }
On the other hand, achieving vertical alignment with horizontal one might be more complicated than usual.
body{ padding: 0; //required to remove that distance line margin: 0; //required to remove that distance line } #distance { width:1px; height:50%; background-color:#fc6; margin-bottom:-13.75em; /* half of container's height */ float:left; } #container { margin:0 auto; /* horizontal align */ position:relative; /* position on top of distance */ text-align:left; height:27.5em; width:45em; clear:left; background-color:#ff9; border:1px solid #c93; border-top-color:#fff; border-left-color:#fff; }
Basically we will need two tag instead of just one container block.
<div id="distance"></div> <div id="container"> hello </div>
The above will give you a center alignment on the center that work even for IE5.5.
Cross Browser Align Center With Absolute
There are many ways to position at the center of the screen when your element is position absolute.
#container{ width: 100px; height: 100px; margin-left: -50px; margin-top: -50px; left: 50%; top: 50%; position: absolute;
You can visit Tutorial: How to align center on the screen when using position absolute with CSS for explanation and other ways of align center when position absolute.
Cross browser Min Width/Height
This is pretty useful for anyone who wish to design your website with a minimum width or height
#container{ width: 100px; width: auto !important; min-width: 100px; height: 100px; height: auto !important; min-height: 100px; }
Cross browser Opacity
The introduce of IE8 has change cross browser opacity a little.
selector { opacity: .75; /* Standard: FF gt 1.5, Opera, Safari */ filter: alpha(opacity=75); /* IE lt 8 */ -ms-filter: "alpha(opacity=75)"; /* IE 8 */ -khtml-opacity: .75; /* Safari 1.x */ -moz-opacity: .75; /* FF lt 1.5, Netscape */ }