Skip to content

Instantly share code, notes, and snippets.

@bramstein
Last active September 5, 2015 07:34
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bramstein/457189 to your computer and use it in GitHub Desktop.
Save bramstein/457189 to your computer and use it in GitHub Desktop.
Detect sub-pixel word- and letter-spacing.
var subpixelWordSpacing = false;
if (document.defaultView && document.defaultView.getComputedStyle) {
// Store the original word spacing on the document element
var originalWordSpacing = document.defaultView.getComputedStyle(document.documentElement, null).wordSpacing;
// Set the word-spacing to half a pixel
document.documentElement.style.wordSpacing = '0.5px';
// This will return either 0px or 1px if sub-pixel word-spacing is not supported, otherwise
// it will return 0.5px.
subpixelWordSpacing = document.defaultView.getComputedStyle(document.documentElement, null).wordSpacing === '0.5px';
// Restore the original word-spacing
document.documentElement.style.wordSpacing = originalWordSpacing;
}
@stephen-uac
Copy link

Wouldn't this make more sense to start off with subpixelWordSpacing set as false? Checking the document.defaultView exists may be false and then leave subpixelWordSpacing as true in cases where the browser doesn't support it.

@CrocoDillon
Copy link

My thoughts exactly. And maybe store the original value so you can restore it properly instead of resetting to 0.

@bramstein
Copy link
Author

@stephen-uac, @CrocoDillon: excellent feedback! I only used this as a quick test to see if sub-pixel word spacing was supported or not. The changes you suggested make it a lot more robust. I've updated the Gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment