Getting started with CSS Tricks - Tutorial, CSS Code Examples


Add Body Class Just For IE
Add Spaces to Dock in OS X
This is absolutely not HTML related, but by sheer demand, I needed to add it somewhere. T...
Base64 Encode of 1x1px Transparent GIF
Just in case you need one. You can stretch it out to fill space as needed.
Basic Microformatted hCard
A basic address and URL, marked up using Microformats.
Button With Line Breaks
Your best bet is a <button> so you can use a <br> i...
Comments in HTML
Cufon 101
1. Include the Java...
Embedding Flash
This is different than the default code that Flash provides. That typically involves the ...
Embedding Quicktime
Quicktime still requires the double-object method to get it done across all browsers. Not...
Embedding Windows Media
Valid technique, as it doesn't need the <embed> tag.
Empty Table Markup
Example Form Markup
Form Submission Opens New Tab/Window
You probably knew that you could force a link into opening a new tab or window with the t...
Get Directions Form (Google Maps)
Get Rid of White Flash when iframe Loads
Hides iframe until fully loaded.
HTML5 Article Structure with hNews
The spec for hNews. ...
HTML5 Page Structure
iPhone Calling and Texting Links
This is the calling one (probably more useful if the clickable text is words, as the iPho...
Keep Flash Behind Other Elements
For example, a dropdown menu going "behind" a flash movie, or staying on top of a lightbo...
Left & Right Halves Layout
Lorem Ipsum Paragraph
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis eges...
Mailto Links
Make IE 6 Crash
This is absolutely NOT recommended for use in any sort of "real" website scenario. It's j...
Meta Refresh
The redirects to the provided URL in 5 seconds. Set to 0 for an immediate redirect.
Meta Tag For Forcing IE 8 to Behave Like IE 7
Meta Tag to Prevent Search Engine Bots
To prevent all search bots from indexing a page:
Multiple File Input
File inputs can have an attribute of "multiple" which then allows multiple files to be se...
Open Link in a New Window
Post Data to an iframe
Doesn't take any JavaScript or anything. You just have the form's target attribute match ...
Proper Tags for Displaying Content Edits
The proper way to mark up changes to an HTML document, when you wish to retain the old co...
Responsive Meta Tag
I tend to use this:
Serving Up Universal IE 6 Stylesheet
All good browsers plus IE 7 and up get REGULAR-STYLESHEET.css, browers IE 6 and below get...
Set iPhone Bookmark Icon
Place this in your <head> section, and set the href attribute to an image to a 57px...
Standard List Navigation
Start a Web Server With One Terminal Command on OS X
I've searched for this three times this week, so I figured I'd better make sure I have a ...
Stop IE Page Load Flicker
Otherwise known as Fajax (fake ajax). For example, when submitting a form and the next pa...
Test Page
A simple XHTML 1.0 Strict page structure that includes: Basic CSS Reset...
Tooltips for Acronyms
I love CSS
Top & Bottom Halves Layout
Turn Off Autocomplete for Input
Just use the autocomplete attribute:
Use Firebug in Any Browser
Just include this script on the site and you'll get a Firebug console that pops up for de...
Video For Everybody (HTML5 Video with Flash Fallback)
View Source of RSS Feed in Firefox
Firefox likes to assume when you click on a link to an RSS feed that you want to subscrib...
XHTML 1.0 STRICT Page Structure
“Shake” CSS Keyframe Animation
This assumes the use of an autoprefixer.
“Stitched” Look
A Complete Guide to Flexbox
A Complete Guide to Grid
CSS Grid Layout is the most powerful layout system available in CSS. It is a 2-dimensiona...
Absolute Center (Vertical & Horizontal) an Image
Accessibility/SEO Friendly CSS Hiding
All Stylesheet Media Types
Animated Grainy Texture
The DayTrip website uses a neat effe...
Basic Link Rollover as CSS Sprite
Basics of Google Font API
Better Helvetica
Blurry Text
Make the text color transparent but add a shadow:
Bouncy Animated Loading Animation
Just some funzies with CSS3 animations. If you are worried about super deep browser suppo...
Browser Specific Hacks
Center DIV with Dynamic Height
Centering a Website
Change Autocomplete Styles in WebKit Browsers
We got a nice tip from Lydia Du...
Change Text Selection Color
Comments in CSS
Common Unicode Icons
Compress CSS with PHP
Start your CSS files with this PHP (and name it style.php):
Corner Ribbon
Cross Browser Inline-Block
Cross Browser Opacity
These days, you really don't have to worry about opacity being a difficult thing cross-br...
Cross-Browser hr Styling
Cross-Browser Min Height
CSS Box Shadow
Used in casting shadows off block-level elements (like divs).
CSS Conic Gradient
A conic gradient is similar to a
CSS Diagnostics
Find mistakes in HTML and highlight the crap out of them.
CSS Font Families
CSS Grid Starter Layouts
This is a collection of starter templates for layouts and patterns using
CSS Hacks Targeting Firefox
CSS Linear Gradient
Perhaps the most common type of gradient we see in web design is the linear-gradien...
CSS Only Image Preloading
One big reason to use image preloading is if you want to use an image for the background-...
CSS Radial Gradient
When we talk about gradients, it's worth beginning with the fact that gradients are an im...
CSS Repeating Gradients
Repeating gradients take a trick we can already do with the creative use of color-s...
CSS Text Shadow
Regular text shadow:
CSS Triangle
CSS3 Zebra Striping a Table
Custom Checkboxes and Radio Buttons
The selectors here are specific to Wufoo markup, but the concepts at work can work for an...
Custom File Input Styling in WebKit/Blink
Custom Radio Buttons
Diagonal Graph Paper Gradient
#example-gradient { height: 200px; margin: 0 0 20px 0; background-color: #e...
Drop Caps
End Articles with Ivy Leaf
Exactly Center an Image/Div Horizontally and Vertically
Expanding Boxes Navigation
From the v8 design of CSS-Tricks.
Fancy Ampersand
Dan Cederholm has long used the Baskerville Italic ampersand, and tells us to
Fixed Footer
Fixed Positioning in IE 6
Flip an Image
You can flip images with CSS! Possible scenario: having only one graphic for an "arrow", ...
Fluid Typography
Getting right to the code, here's a working implementation:
Font Shorthand
Font Stacks
Force File Upload Input Button To Right Side In WebKit
Firefox and IE have the "choose file" button to the right of the filepath, while Webkit p...
Force Vertical Scrollbar
Forcing Grayscale Printing
At the time of this writing, this will only work in Chrome 18+, but it's
Give Clickable Elements a Pointer Cursor
Glowing Blue Input Highlights
Like mid-2012 Twitter.
Gradient Text
This is WebKit only, but is the cleanest way to accomplish it as the text remains editabl...
Gradient Underlines
Handling Long Words and URLs (Forcing Breaks, Hyphenation, Ellipsis, etc)
There are times when a really long string of text can overflow the container of a layout....
Handling Long Words and URLs (Forcing Breaks, Hyphenation, Ellipsis, etc)
We've moved this snippet to our canonical snippet on this subject. ...
Hexagon With Shadow
<div class="hexagon"><span></span></div>
Hide Scrollbar in Edge, IE 10/11
You can make it auto-hiding instead of always-showing:
Internationalization Language CSS
iPad Orientation CSS
iPad-Specific CSS
Keyframe Animation Syntax
Layered Paper
Link Pseudo-Classes (In Order)
Make “Pre” Text Wrap
Text in <pre> tags doesn't wrap by default. For example, see the code snippet below...
Make Non-Password Inputs Use Bullets (or Bullet Alternatives)
This works on texty inputs (e.g. text, email, etc) but you cannot change actual password ...
Media Queries for Standard Devices
If you think responsive's simple, I feel bad for you son. We got 99 viewports...
Meyer Reset
Mixins for Rem Font Sizing
The rem font-size unit is similar to em, only instead of cascad...
Momentum Scrolling on iOS Overflow Elements
Web pages on iOS by default have a "momentum" style scrolling where a flick of the finger...
Monotone an Image with CSS
You can always apply a filter to an element to make it monotone in the grayscale sense:
Multiple Backgrounds Syntax
Browsers that support multiple backgrounds (WebKit from the very early days, Firefox 3+) ...
Multiple Borders
Multiple Columns
Here is an example of a simple three-column class:
Named Colors and Hex Equivalents
Color Name HEX Color
Nested & Expandable Folders
This was a demo originally by Martin Ivanov, utilizing hidden checkboxes and adjacent sib...
Noise Data URI Image
Non-Form Fieldset Look
<section class="fieldset"> <h1>This is not a fieldset</h1> &l...
Not-Terrible Image Resizing in IE
Orientation Lock
Page Curl Shadows
Perfect CSS Sprite / Sliding Doors Button
Picross Style Buttons
As in, the game PICROSS3D.
PNG Hack/Fix for IE 6
Prevent Bounce Scroll in Lion
Just make sure you zero out the margin and padding on those elements as well (normal in a...
Prevent Superscripts and Subscripts from Affecting Line-Height
Print URL After Links
Quality Abbreviations
Slightly lighter color (assuming your text is black), dotted bottom border, and a questio...
Remove Button Text in IE7
Remove Dotted Link Borders
Dotted borders around links are an accessibility feature most browsers have by default. I...
Remove Gray Highlight When Tapping Links in Mobile Safari
Remove Margins for First/Last Elements
It can sometimes be desirable to remove the top or left margin from the first element in ...
Remove Scrollbar from Textarea in IE
By default all versions of IE have a scrollbar on textareas, even when they are empty.
Removing Dotted Outline
Retina Display Media Query
For including high-res graphics, but only for screens that can make use of them. "Retina"...
Reversing Text
For right-to-left languages, you can swap the default left-to-right layout in most browse...
Rounded Corners
Scale on Hover with Transition
Bring your own prefixes!
Signify “PDF Bombs”
Any ol' anchor link can be a link to a PDF document, but clicking a link like that thinki...
Simple and Nice Blockquote Styling
The blockquote displays in standards-compliant browsers with the "big quotes before" effe...
Slide In Image Boxes
From the footer of the v8 design of CSS-Tricks.
Smiley Slider
Requires jQuery and jQuery UI for the actual slider. The face is made from elements made ...
Solarized Theme for CodeMirror and Prettify
Here's for Googl...
Spinny Leaf Menu
<nav> <ul class="top-menu"> <li><a href=#>Home</...
Stacked Paper Effect
A popular design technique is to create a content container that looks like a sheet of pa...
Standard CSS Image Replacement
h1#logo { width: 200px; // width of image height: 100px; // height of image...
Star Wars Crawl Text
The opening to Star Wars is iconic. The effect of text scrolling both up and away from th...
Sticky Footer
Works great if you can apply a fixed height to the footer.
Style Links Depending on Destination
Style Override Technique
The :placeholder-shown pseudo-class selects the input element itself...
System Font Stack
Defaulting to the system font of a particular operating system can boost performance beca...
Text Dripping Blood
Text Rotation
The Clearfix: Force an Element To Self-Clear its Children
This will do you fine these days (IE 8 and up): ...
Toggle Visibility When Hiding Elements
The development team at Medium have discussed some
Top Shadow
Shadow along the top edge of the website, like this:
Transparent Background Images
There is no CSS property background-opacity, but you can fake it by inserting a pseudo el...
Transparent Inside Border
Triangular List Bullets
Truncate String with Ellipsis
All the following are required, so the text must be in a single straight line that overfl...
Tucked Corners
Turn Off Number Input Spinners
WebKit desktop browsers add little up down arrows to number inputs called spinners. You c...
Two-Color Three-Dimensional Blocks and Text
We can use multiple text-shadow and box-shadow values to create...
Typewriter Effect
Useful CSS3 LESS Mixins
Using @font-face
The @font-face rule allows custom fonts to be loaded on a webpage. Once adde...
@extend Wrapper a.k.a Mixtend
When extending a selector with the @extend directive, Sass doesn’t take the ...
Advanced Type Checking
This collection of functions is for testing if the value of a variable is of a certain ty...
BEM Mixins
The best introduction to BEM is from
Black and White Opacity Functions
It's pretty common to need a bit of transparent black or white. In CSS, you can do:
Caching the Current Selector (&) in Sass
The & character in Sass is unique in that it represents the current sele...
Centering Mixin
Assuming the parent element has position: relative;, these four properties w...
Clamping a Number
In computer science, we use the word clamp as a way to restrict a number between...
Color Luminance Function
When digging deep into color theory, there is something called
Correctly Adding Unit to Number
When converting a unitless number to a length, duration, angle or whatever, people tend t...
Covering Mixin
I find myself using these properties together all the time, which is typically a good opp...
CSS Triangle Mixin
There is a fairly popular CSS hack using transparent borders on a 0-width / 0-height elem...
Custom Scrollbars Mixin
Scrollbars are one of those UI components that are present on almost every page of the in...
Deep Get/Set in Maps
When working on complex Sass architectures, it is not uncommon to use Sass maps to mainta...
Easing Map Get Function
Bézier curves can be used to add beautiful effects to CSS transitions and animations. Typ...
Fix a Number to N Digits
When dealing with numbers in JavaScript or any other programming language, there is a way...
Functional Programming Functions
For library makers and framework builders, having a couple of extra functions to dynamica...
Maintain Aspect Ratio Mixin
Material Shadows Mixin
Material Design
Mixin for Offset Positioning
If there is one shorthand CSS dramatically misses, it is the one making it possible to de...
Mixin to Manage Breakpoints
Responsive Web Design creations often exist over several different breakpoints. Managing ...
Mixin to Prefix Properties
In case you're interested in handling your own CSS vendor prefixing (rather than, say,
Mixin to Qualify a Selector
There is no easy way of qualifying a selector from within its associated ruleset. By qual...
Opposite-direction Function
Sass framework Compass...
Placing Items on a Circle
It can be quite challenging to place items on a circle with CSS. Usually, we end up relyi...
Power Function
While very helpful with arithmetic, Sass falls a bit short with mathematical helper funct...
Px to Em Functions
We've talked about "Why Ems?"
Sass Things for Links
Simple Asset Helper Functions
Dealing with paths is always a bit annoying, you will concede. Fortunately, it is extreme...
Simplifying Contexts and Events
Sass can somehow be a little of a black box, especially for young developers: you put som...
Sorting Function
Sass does not provide any built-in way to sort a list of values. Thanks to string manipul...
Str-replace Function
Sass provides a collection of handy functions to manipulate strings, however there is no ...
Strip-unit Function
There is a lot of confusion around the way units work in Sass. Yet, they work exactly as ...
Striped Gradient Mixin
A popular way to draw stripes in CSS it to define a linear-gradient with overlapping colo...
Tint and Shade Functions
Both lighten and darken functions manipulate the lightness of a...
Use a Sass Variable for a Selector
Say you need to use a certain selector in multiple places in your code. It's not tremendo...
Viewport Sized Typography with Minimum and Maximum Sizes
Declaring font sizes in
Adobe Illustrator Export Options
This is less of a snippet and more of a reminder for something I look up often. When crea...
Curved Text Along a Path
We can flow text along a curved line with three tools built right into SVG: <pat...
Shape Morphing Icons in Button on Click
The idea here is use an SVG icon in a button and swap that icon out for another when the ...
SVG Knockout Text
The idea here is to imagine three layers stacked on top of one another where the top laye...
SVG Patterns
The SVG <pattern> attribute allows us to define patterns inside of our...
Text Lock-Up
301 Redirects
This is the cleanest way to redirect a URL. Quick, easy, and search-engine friendly. Reme...
Active Gzip Compression
Compression reduces response times by reducing the size of the HTTP response. Gzip is the...
Allow Single URL Through .htaccess Password Protection
This code is useful for multi environment setups (staging, production, etc.) it allows yo...
Append / Prepend Files
Rather than having to call / include a file you need on every single page, you can have t...
Custom Error Pages
ErrorDocument 400 /400.html ErrorDocument 401 /401.html ErrorDocum...
Denying and Allowing Access
Different Directory Index Page
Normally index.html or index.php is the default page a server serves up when visiting a d...
Fancy Indexing
Adds fixed width fonts, file size and date, sort capability. Propagates to higher level d...
Force charset utf-8
If you can not change the configuration of Apache server, use this code to force decoding...
Force Correct content-type for XHTML Documents
Most webservers serve XHTML content as text/html what is definitly the right way...
Force Favicon Requests to Correct Location
For whatever crazy reason, perhaps evil-doing site scanners, requets to a web server for ...
Force Files to Download (Not Open in Browser)
AddType application/octet-stream .csv AddType application/octet-stream .xls AddTy...
RewriteEngine on RewriteCond %{HTTPS} !on RewriteRule (.*) https:/...
Get The Dreamhost Stats Page Working on a WordPress Site
For websites hosted with Dreamhost, you have an analytics page by default at yoursite.tld...
iPad Detection
Of course, the iPad is a pretty large screen and a fully capable browser, so most website...
iPhone Catcher
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_USER_AGENT} .*...
Password Protect Folder(s)
Put in .htaccess file in the directory you are trying to protect:
PHP Error Logging
Log errors to a file, and prevent showing them to the user. Make sure that the file exist...
Prevent Image Hotlinking
RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yourdomain\.com/ [NC...
Remove File Extention from URLs
RewriteRule ^about$ about.php [L] That little bi...
Serve SVG with the Correct Content Type
If you are trying to use SVG like <img src="image.svg"> or as a CSS
Set Expires
Setting "expires" tells browsers downloading these files that they don't need to request ...
Shock Teenage Gangsters with wp-config Redirect
Funny email from a reader, that I figured would make a good post: This...
Subdirectories URL Internally Redirect to Query String
The URL in the browser would be:
Temporary Maintenance using Mod_Rewrite
# Don't forget to turn on the rewrite engine RewriteEngine on #...
Use PHP inside JavaScript
This has only really been tested on Media Temple (gs) servers. In the folder with ...
You should really be doing one or the other. For consistency, as well as SEO's, sake....
“Go Back” Button
Browsers already have "back" buttons, so you'd better have a darn good reason for needing...
1024×768 Bookmarklet
The days of 800x600 screens are all but over, but most of us still try to accommodate 102...
Add a Number to Two Variables At Once
You can initialize two variables to the same value at once, kinda:
Add Data Attribute of User Agent
Add To Favorites (IE)
<a href="" onclick="window.external.AddFavorite(this.href,this....
addClass Function
If you are going library-free, you might need to roll your own function like this.
addEventListener Polyfill
Array of Country Names
Async Script Loader with Callback
Async Sharing Buttons (G+, Facebook, Twitter)
Some of these services already (smartly) provide their scripts in an async fashion, this ...
Auto Select Textarea Text
Basic Alert
Bind Different Events to Click and Double Click
You might want a link to have a special action when double-clicked which prevents the def...
Break Out of iframe
Call Function with Random Timer
Check if font-family is Honored
Check if Function Exists Before Calling
When using scripts that are shared between different areas of a site, there may be cases ...
Check if Number is Even/Odd
Clear Field on Focus
Comments in JavaScript
Convert Polygon to Path Data
I've had to do this a few times recently so I thought I'd save the method. StackOverflow ...
Cookie Getter/Setter
Cross-Browser Dependency-Free DOM Ready
Denis Ciccale's versio...
CSS for when JavaScript is Enabled
Current Page with JavaScript
This is like a replacement for PHP's SCRIPT_NAME with JavaScript.
Default Arguments for Functions
Detect Internet Explorer
Detect Javascript On/Off, With Notification
Different Stylesheet Pending the Time of Day
Different Stylesheets for Different Days of the Week
Empty an Array
This is one of the fastest and easiest ways of emptying an array. Of course there are may...
Error-Free Console Logging
Fix IE 10 on Windows Phone 8 Viewport
Format Currency
This function will round numbers to two decimal places, and ensure that the returned valu...
Get All Possible DOM Events
You can get an array of all the events that start with "on" (e.g. onclick) by running thi...
Get Object Size
As in, the number of keys.
Get URL and URL Parts in JavaScript
JavaScript can access the current URL in parts. For this URL:
Get URL Variables
Get YouTube Key from a Link
Global Variables
Declare variable outside of the function...
htmlEntities for JavaScript
htmlentities() is a PHP function which converts special characters (like <) into their...
Inject New CSS Rules
If you need to change the style of an element with JavaScript, it's typically better to c...
Input with Disappearing Background Image
This replicates the functionality of the standard embeddable Google Search fields. They h...
JavaScript Array Contains
Javascript objects are really nice, but sometimes they are missing some useful little fun...
JavaScript MD5
JavaScript Required Content with Fallback Content
JavaScript-required area is hidden with inline CSS, and then shown after it loads with a ...
KeyboardEvent Value (keyCodes, metaKey, etc)
When a KeyboardEvent fires, you can test which key was pressed because that ...
Lazy Loading Images
Use a blank.gif as the src of images, and include the wid...
Lighten / Darken Color
The CSS preprocessors Sass and LESS can take any color and darken() or lighten() it by a ...
Loop Over querySelectorAll Matches
You can loop over Arrays easily in JavaScript with forEach, but unfortunatel...
Loop Through Array Without Wasteful Lookups
Find the length of the array before using it in the for function, so it ...
Make HTML5 Elements Work in Old IE
So that the DOM (and thus CSS) recognizes them as real elements:
Modern Event Handling
Move Cursor to End of Input
Where el is a reference to an input or textarea.
Multiline String Variables in JavaScript
This works:
Namespaced Javascript Template
Self invoking anonymous function assigned to the yournamespacechoice global ...
PageVisibility API
<!DOCTYPE HTML> <html> <head> <script type="te...
Perform Function At Timed Intervals
Perform a function every one second:
Prevent Background Image Flickering in IE
Prevent Embedded JavaScript from Failing Validation
Ever see that CDATA stuff in JavaScript and wonder what it was for? It is to prevent the ...
Print Object To Screen
PHP has a nice print_r function ...
Put Comma Values in Numbers
This function assumes what is being submitted to it is a string, with a decimal point and...
Random Hex Color
Redirect Mobile Devices
Redirect to SSL
Remove an Element
For whatever reason, an element can't destroy itself in JavaScript. jQuery
Remove Inline Styles
This function also preserves hidden content.
Remove the Last Character from a String
Replacements for setInterval Using requestAnimationFrame
When it comes to animation, we're told that setInterval is a bad idea. Becau...
Saving contenteditable Content Changes as JSON with Ajax
Elements with the contenteditable attribute can be live-edited right in the ...
Select Random Item from an Array
Strip HTML Tags in JavaScript
Strip Numbers from a String
Strip Whitespace From String
Whitespace, meaning tabs and spaces.
Support Tabs in Textareas
Normally the tab key moves to the next focusable thing. This inserts a tab character in i...
Test for Internet Explorer in JavaScript
Test if dragenter/dragover Event Contains Files
HTML5 drag and drop is great for handling file uploads. But if that's the only thing you ...
Test if Element Supports Attribute
Not all browsers support all attributes on all elements. There are a number of new attrib...
Test if Mac or PC with JavaScript
User Agent testing sucks, but sometimes you need it for subtle things. In my case I was u...
Toggle (Show/Hide) Element
Unescape HTML in JS
Validate HTML Bookmarklet
Viewport Size, Screen Resolution, Mouse Postition
This code is cross-browser compatible and checks the dimensions of the viewport, the scre...
Word Count Bookmarklet
Add to bookmarks bar, select text, click it to get the word count.
A jQuery hasAttr() Equivalent
jQuery doesn't really have an .hasAttr() function. You might assume that it ...
Add :nth-of-type to jQuery
$.expr[':']['nth-of-type'] = function(elem, i, match) { var parts = match[3]....
Add Active Navigation Class Based on URL
Ideally you output this class from the server side, but if you can't... Let's s...
Add Non-Breaking Space on Title to Prevent Widows
Adding/Removing Class on Hover
Animate Height/Width to “Auto”
It's not possible to do thing.animate({ "height": "auto" });. So this is Dar...
Append Site Overlay DIV
Automatically Discover Document Links And Apply Class
Better Broken Image Handling
Missing images will either just display nothing, or display a [ ? ] style box when their ...
Browser Detection + Apply Classes to HTML Element
Calculate Distance Between Mouse and Element
Change WMode with jQuery
If you don't set the wmode on a flash embed it will float over the top of an overlay whic...
Check for Empty Elements
Do something for each empty element found:
Check if Checkbox is Checked
Say that 10 times fast =). Find out if a single checkbox is checked or not, return...
Check if Element Exists
Check if Element is inside Another Specific Element
Replace the first selector with the child you are testing and the second selector with th...
Check if Event was Triggered or Native
Check if jQuery is Loaded
Clear a File Input
You can just clone it and replace it with itself, with all events still attached. ...
Clear Default Search String on Focus
Click Once and Unbind
Have something happen on a click event, but only once! Unbind the click handler after the...
Combine Slide and Fade Functions
Compare jQuery Objects
You can't really compare if two jQuery objects are the same...
Cycle Through a List
This code will cycle through an unordered list with an ID of 'cyclelist'. Can be used on ...
Detect First Visible Element of Certain Class
Adds a class of "first" to the first element that has a class of "activity" that is visib...
Disable / Re-enable Inputs
Disable Parent Links in Nested List Navigation
jQuery code that disables parent links for drop down menus. The menu should be built as n...
Display Browser and Version
This is jQuery specific, and contains a bit of a hack/fix for dealing with Chrome. This w...
Display Last Tweet
The code below no longer works as-is with the Twitter API update t...
Display Latest FeedBurner Post
This snippet will display the latest post in a specified FeedBurner feed. Just set the UR...
Display Loading Graphic Until Page Fully Loaded
<!DOCTYPE html> <html class="no-js"> <head> <meta charset=...
Display Only First X Divs, Toggle Rest
Done Resizing Event
If you're used to something like
Draggable without jQuery UI
It doesn't have all the fancy callbacks and options, but hey, it makes things draggable (...
Equalize Heights of Divs
Exclude $(this) from Selector
Let's say you want to attach a click handler to every link on a page. The function for th...
Fade Image Into Another Image
Make a div that is the exact size of the image. This div will have a background image app...
Fade One Image to Another Menu
Make a CSS sprite image, with the top half and the bottom half being the two images you w...
Fallback for CDN hosted jQuery
Several big companies offer copies of jQuery hosted on their CDN's (Content Delivery Netw...
Find all Internal Links
Find all links that start with the sites domain, a slash, relative file path, or a hashta...
Find and Wrap Ampersands
Load th...
Fire Event When User is Idle
See the two commented lines below, that is where you can insert code for things to do whe...
Fix Min/Max-Width for Browsers Without Native Support
This script checks all elements with a class of .fixMinMaxwidth and observes the window. ...
Fix Select Dropdown Cutoff in IE 7
Run (at least the "Usage" part below) after you've loaded jQuery and either at the end of...
Fixing .load() in IE for cached images
The .load() function fires when the element it's called upon is fully loaded. It is commo...
Fixing IE z-index
This isn't an end-all-be-all solution to fixing all weird IE z-index issues, but it certa...
Force iframe to Reload
Get an Images Native Width
If you select and image with jQuery and then use .width(), you'll get the im...
Get Query Params as Object
Nicholas Ortenzio
Highlight All Links To Current Page
Highlight Related Label when Input in Focus
Image Preloader
Very easy way to preload images which are needed later (e.g. when a hover is performed)
Inputs That Remember Original Value
Insert Element Between Other Elements
For example, if you have five paragraphs in a row and you need to insert a break tag in b...
jQuery Duplicate Plugin
jQuery JSON getting with error catching
jQuery has a built in function called getJSON() to help making AJAX requests for JSON dat...
jQuery Plugin Template
Replace instances of "yourPluginName" with your actual plugin name. The stuff about "radi...
jQuery Sticky Footer
In general the
jQuery Tweetify Text
jQuery Zebra Stripe a Table
Konami Code
Link Nudging
Load jQuery Only If Not Present
Say you were going to do an include on a whole bunch of pages, and inside of that include...
Load Only a Section of a Page
Loading jQuery
Make Entire Div Clickable
Update: this probably isn't a thing you need to rely on JavaScript for a...
Make jQuery :contains Case-Insensitive
Move Clicked List Items To Top Of List
Assuming HTML like this:
Move Cursor To End of Textarea or Input
Code to move the cursor to the end of the current text within in the input, rath...
Setting the value of a textarea moves the cursor to the end. So you just need to save the...
Open External Links In New Window
outerHTML jQuery Plugin
innerHTML() is native and returns the contents of a DOM node (e.g. <span>I li...
Partial Page Refresh
Refresh certain elements of a page using jQuery after a set amount of time, can be used w...
Password Strength
Paste Events
Persistant Headers on Tables
When you scroll down a page with a long table on it, typically the header of the table sc...
Remove Specific Value from Array
Resize iFrame to Fit Content (Same Domain Only)
Normally you set and width and height for iframes. If the content inside is bigger, scrol...
Run JavaScript Only After Entire Page Has Loaded
Scroll Page Horizontally With Mouse Wheel
Select Element Only if Children are Not Animated
Select List Item Only If Doesn’t Contain Another List (and is top level)
I realize this is rather specific, but I had to write this selector earlier to fix a prob...
Serialize Form to JSON
Set/Clear Default Input Value
Shuffle Children
Nice clean version of a
Shuffle DOM Elements
This is from James Padolsey. Check out
Simple Auto-Playing Slideshow
Simple jQuery Accordion
Sliding Background Links
Smarter Event Binding
Styled Popup Menu
This idea is from and how they handle the dropdowns for things like
Target Only External Links
Test if at least one checkbox is checked
In this example, a submit button is disabled if none of the checkboxes are checked and en...
Toggle Text
Let's say you have a link to show more options which expands a list of options. It's says...
Track Window Resizes through Google Analytics
Trigger Click on Input when Label is Clicked
Labels should have "for" attributes that match the ID of the input they are labeling. Thi...
Triple Click Event
Underline Individual Words
There is no CSS for applying an underline (text-decoration: underline;) only...
Validate Age
This snippet presupposed an HTML form with and ID of "age-form" and three inputs (text or...
Window load event with minimum delay
window.load can fire super duper fast if the page is cached. If you want to use that even...
Working with Attributes
Remove Width and Height Attributes From Inserted Images
When you upload an image through the WordPress media uploader and then insert it into the...
“Edit This” Button on Posts and Pages
Add Category Name to body_class
The b...
Add class to links generated by next_posts_link and previous_posts_link
These two functions create anchor links, and you can customize a lot of it, but it's impo...
Add/remove contact info fields
User profiles in WordPress have these fields for Contact Info by default: E-mail, Website...
Admin Panel Link Only For Admins
Allow SVG through WordPress Media Uploader
NOTE: As of 4.7.1 this isn't working exactly as published here anymore.
Apply Custom CSS to Admin Area
Add to the functions.php file:
Automatic Social Media Links
This would go inside the loop, probably underneath the_content(), probab...
Base Threaded Comments Styling
Bloginfo Shortcode
The bloginfo() function in WordPress gives you access to lots of useful information about...
Change Avatar Size
The wp_list_comments function has a parameter to change the default (48px) size to anywhe...
Custom Database Error Page
Put a file called "db-error.php" directly inside your /wp-content/ folder and WordPress w...
Custom Loop/Query Based on Custom Fields
Last updated by
Customize Comments Markup
In a typical WordPress theme you output the entire list of comments for a Post/Page by us...
Customize Login Page
You know, the one typically at These are things you would put ...
Detect Gists and Embed Them
Just post a link to a GitHub Gist ...
Disable Automatic Formatting
Disable Automatic Formatting Using a Shortcode
function my_formatter($content) { $new_content = ''; $pattern_full ...
Display a Tag Cloud
Display Author Info
The image that shows for the author comes from the email address set for that user which ...
Display Image Next To Each Tag
<?php $posttags = get_the_tags(); // Get articles tags $home = get_bloginfo('u...
Display Post Divider In Between Posts
Right before the closing of the The Loop, insert this code:
Dump All Custom Fields
WordPress has a built in function, the_meta(), for outputting all custom fields. But this...
Dynamic Title Tag
Embed a Page inside a Page
Enable All Possible Post Formats
For your functions.php file in the theme.
Facebook “Like” Button for WordPress
Some very easy copy-and-paste code here to add to the template for blog posts to allow fo...
Find ID of Top-Most Parent Page
This will find what the ID is of the top-most parent Page, in a nested child page. For ex...
Get Content by ID
Apparently there is no succinct WordPress function for just returning the content of a pa...
Get Featured Image URL
Post thumbnails are pretty useful and pretty easy to use in WordPress. Simply add:
Get ID from Page Name
Add to functions.php file:
Get The First Image From a Post
Let's say you wanted to use the
HTML5 Shim in functions.php
Might as well keep your header.php clean and insert the shim from the functions.php file....
ID the Body Based on URL
If Page Is Parent or Child
There are built in conditional WordPress functions for testing for a page:
Include Any File From Your Theme
Include jQuery in WordPress Theme
The following is the best way to go about it. Add the following to the theme's functions....
Increase Custom Fields Dropdown Limit
For your functions.php file or custom plugin:
Insert Images with Figure/Figcaption
For a simple plugin or functions.php file:
Insert Images within Figure Element from Media Uploader
For your functions.php file or a functionality plugin:
List Posts, Highlight Current
WordPress lacks a wp_list_posts() function that might seem logical go with the robust and...
Login/Logout and User Welcome
Make Archives.php Include Custom Post Types
Archives.php only shows content of type 'post', but you can alter it to include custom po...
Move WordPress Admin Bar to the Bottom
Pre WordPress 3.3 only. Either add this CSS to your CSS file, add all th...
Natural Sort Using Post meta_key
Output Excerpt Manually
There is always
Paginate Custom Post Types
Prevent CSS Caching
Prevent Search Bots from Indexing Search Results
In the <head> section of your header.php file:
Recent Posts Function
Remove Admin Bar For Subscribers
You might want open registration on your WordPress site so that (for one small example) p...
Remove Gallery Inline Styling
Remove LI Elements From Output of wp_nav_menu
You can remove or change the <ul> container that you get by default wi...
Remove Link to the WLW Manifest File
Kind of pointless to include this unless you actually use Windows Live Writer to write yo...
Remove Paragraph Tags From Around Images
In case you want to have <img> in your content but not have them get "...
Remove Private/Protected from Post Titles
For the functions.php file in your theme:
Remove Specific Categories From The Loop
Remove the 28px Push Down from the Admin Bar
For your functions.php file:
Remove Whitespace from Function Output
In WordPress, there are many functions which output things for you. For example, wp_list_...
Remove WP Generator Meta Tag
It can be considered a security risk to make your wordpress version visible and public yo...
Removing Jetpack CSS
Jetpack is a WordPress plugin that bring...
Replace Excerpt Ellipsis with Permalink
This is useful if you would like to replace the ellipsis [...] from the excerpt with a pe...
Reset Admin Password in Database
Forget your admin password and don't have access to the email account it's under? If you ...
Reset Admin Password Through Database
You'll need to be able to run SQL on that database, like for example, through phpMyAdmin....
Run a Loop Outside of WordPress
Run Loop on Posts of Specific Category
Shortcode for Action Button
Shortcode in a Template
Shortcodes in WordPress are bits of text you can use in the content area to invoke some k...
Show Your Favorite Tweets with WordPress
Just replace the URL in the fetch_rss line below with the RSS feed to your Twitter favori...
Shrink the Admin Bar / Expand on Hover
A mini plugin:
Spam Comments with Very Long URL’s
Super long URL's are a sure fire sign the comment is spammy. This will mark comments with...
the_category with Excludes
The WordPress function
Turn On More Buttons in the WordPress Visual Editor
These buttons (like one for adding an <hr> tag) aren't there by defaul...
Turn on WordPress Error Reporting
Comment out the top line there, and add the rest to your wp-config.php file to get more d...
Using Custom Fields
Year Shortcode
For the functions.php file:
Adjust Server Time
Sometimes the time set on your server isn't accurate to what your local time is. If you c...
Append Login Credentials to URL
The example here is if you had a form on a website that when submitted, needed to use tha...
Append Non-Breaking Space Between Last Two Words
Applying Even/Odd Classes
Associative Array Syntax
Automatic Copyright Year
Automatic Mailto Links
Basic Database Connection, Random Query, Display Result
Basic SimplePie Usage
You'll need a of copy SimplePie for the include right at the top here.
Build a Calendar Table
Calendar Function
Change Date from dd/mm/yyyy to yyyy-dd-mm
Change Graphics Based on Season
Change Month Number to Month Name
Check if File Exists / Append Number to Name
If the file name exists, returns new file name with _number appended so you don't overwri...
Check if Website is Available
Performs a cURL-Request to check, if a website exists / is online
Cleaning Variables
Variables that are submitted via web forms always need to be cleaned/sanitized before use...
Comments in PHP
Concatenate Array for Human Reading
Convert Accented Characters
For instance, if you want to use a string as part of a URL but need to make it safe for t...
Convert BR to Newline
Convert Comma Separated String into Array
Easy way to turn a CSV file into a parseable array.
Convert HEX to RGB
Give function hex code (e.g. #eeeeee), returns array of RGB values.
Count Script Excecution Time
Create Data URI’s
These can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at th...
Create Unique AlphaNumeric
Create URL Slug from Post Title
Regular expression function that replaces spaces between words with hyphens.
Crop Image
Displays a selected chunk of an image. In the example provided, the upper left 100px x 10...
Cross Domain GET Forwarding
When you do an AJAX request on a website, the URL you request from needs to reside on the...
Debugging $_REQUEST
This snippet displays a nice list of all submitted data in a transparent box on the top l...
Detect AJAX Request
The HTTP_X_REQUESTED_WITH header is sent by all recent browsers that support AJAX request...
Detect IE5 or IE6
Detect Location by IP
Returns "City, State" if found otherwise the default set at the top.
Discover and Display Meta Tags
This is a completely styled page which displays meta tag information it pulls from provid...
Display a User Gravatar from an Email Address
Display Array Contents
Display FeedBurner Feed Count
Display Styled Directory Contents
Servers can be configured to show the contents of a directory that doesn't have an index ...
Email Address Validation
Email Protector
English Time to Seconds
Just type in the time you want converted to seconds in english (e.g. "1 hour and 30 minut...
Error Page to Handle All Errors
This is a way to make a single error page for all errors, which is easier to update and m...
Extract Email Addresses
Just pass the string (e.g. the body part of an email) to the function, and it returns an ...
Find All Links on a Page
Here's the basic principal behind spiders.
Find File Extension
Find Highest Numerically Named File
Find the Full Path to a File
Find URLs in Text, Make Links
Force Leading Zero
Generate CSV from Array
Generate Expiring Amazon S3 Link
You don't have to make files on Amazon S3 public (they aren't by default). But you can ge...
Get All-Time Number of MySQL Queries
Get Current File Name
Get Current Page URL
Get FeedBurner Subscriber Count with cURL
Get File Last Updated Date
Get File Size
Get Geo-IP Information
Requests a geo-IP-server to check, returns where an IP is located (host, state, country, ...
Get Image Information
Get Latest Twitter Status
The code below no longer works as-is with the Twitter API update t...
Get Suffix of Given Number/Date
Get Users IP Address
Accounts for proxies:
Get Width/Height of Image
If all you have for an image is the URL, you can still find the dimensions:
Highlight a Substring
Import CSV into MySQL
Increase Maximum PHP Upload Size
Many shared hosts put very low restrictions on the size of the files that can be uploaded...
Insert Element Every nth Loop
When inside of a loop, you can keep track of the iteration number of the loop (shown belo...
Intelligent PHP Cache Control
This code snippet checks if a page has been modified since it was last displayed. If so, ...
Login Function
These functions will log in a user based on a username and password being matched in a My...
Make Random Number
MySQL Backup Class
MySQL Database Access Class
MySQL Restore Class
Options to Truncate Strings
Output Buffering
Pagination Function
Parse JSON
Perform Function on Each Item of an Array
array_map() takes two arguments. The first argument is the function to perform on the sec...
PHP Array Contains
Check if value is in array and outputs Yes or No
PHP Date Parameters
PHP IE Detection
PHP Include
PHP Redirect
PHP Zebra Striping a Table
POST Validation Loop
Quick Alphabetic Navigation
Could be useful for an address book style navigation.
Random Hex Color
Random Slogan Displayer
Create a text file called slogans.txt with permissions that it can be read by the server....
Random String from Pre-Determined Characters
Randomize Background Image
Randomize File Name
Read/Write Files
Return Only One Variable from MySQL Query
RSS Generator
You'll need a MySQL database with a a table called `rss_feed`. In that table there are 3 ...
Sanitize Database Inputs
Send a Text Message
You'll need a TextMagic account a...
Send Email
Separate First and Last Name
Server Side Image Resizer
The code uses PHP to resize an image (currently only jpeg). Using this method, the resize...
Simple Zipcode Range Tester
This regex below tests the provided zip code if it starts with the numbers 096 and that t...
Time Ago Function
This can be used for comments and other from of communication to tell the time ago instea...
Truncate Long String Exactly In Middle
This will truncate a longer string to a smaller string of specified length (e.g. the "25"...
Truncate String by Words
Unzip Files
Update Values of Entire Table
This code assumes you are connected to a MySQL database which has a table with Names and ...
URL Validation
Variable Variables
Zero Padded Numbers