Skip to content

Instantly share code, notes, and snippets.

@thisandagain
Created October 23, 2013 20:54
Show Gist options
  • Save thisandagain/7126577 to your computer and use it in GitHub Desktop.
Save thisandagain/7126577 to your computer and use it in GitHub Desktop.
Kerning... without any gosh darn jQuery! *tableflip*
/**
* Framework-less kerning support for browsers.
*
* @package kern
* @author Andrew Winterman <[email protected]>
* Andrew Sliwinski <[email protected]>
*/
/**
* Export
*
* @param {object} DOM element to apply kerning to
* @param {array} An array of adjustment values for each character
*/
window.kern = function (element, table) {
var text = element.innerHTML;
var split = text.split('');
// Build up sub elements
var elements = '';
for (var i = 0; i < split.length; i++) {
elements += ('<div>' + split[i] + '</div>');
}
// Replace element contents
element.innerHTML = elements;
// Apply styles
var children = element.children;
for (var c = 0; c < children.length; c++) {
children[c].style.display = 'inline-block';
children[c].style.marginLeft = table[c] + 'px';
}
};
<html>
<head>
<title>Kern</title>
<style>
body {
margin: 40px 0 0 0;
padding: 0;
font-family: Helvetica, sans-serif;
}
h1 {
font-size: 6em;
}
#container {
width: 600px;
margin: 0 auto;
text-align: center;
}
</style>
</head>
<body>
<!-- Ye olde container element -->
<div id="container">
<!-- Element to be kerned -->
<h1 id="kernMe">Kerning</h1>
<!-- Some other stuff -->
<p>In typography, kerning (less commonly mortising) is the process of adjusting the spacing between characters in a proportional font, usually to achieve a visually pleasing result. Kerning adjusts the space between individual letter forms, while tracking (letter-spacing) adjusts spacing uniformly over a range of characters.</p>
</div>
<!-- JS -->
<script src="../kern.js"></script>
<script>
var element = document.getElementById('kernMe');
kern(element, [
1, -20, 3, -4, 25, -6, 7
]);
</script>
</body>
</html>
@AWinterman
Copy link

It looks good to me. A few things, but first a caveat: I've never had a need to kern a thing. :)

  • I'd like it to be at least compatible with node-style commonjs. I dislike tacking things onto the side of the window object :\
  • Wouldn't it better to use n-th child css selectors?
  • I had thought it would be better to wrap each element in an inline span and then give it a data-kern="a" attribute, which you can then glob onto with [data-kern]:nth-child(4) or [data-kern="a"]

Finally my work is MIT licensed, so you should feel free to fork it / clone it / steal it / etc. I'm not even sure if you have to list me as an author, although I do appreciate it. ❤️

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