• Stars
    star
    1,492
  • Rank 31,473 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flipping how we define typography in CSS.

Capsize

Capsize


Capsize makes the sizing and layout of text as predictable as every other element on the screen.

Using font metadata, text can now be sized according to the height of its capital letters while trimming the space above capital letters and below the baseline.

npm install @capsizecss/core

Usage

createStyleObject

Returns a CSS-in-JS style object.

  1. Import createStyleObject passing the relevant options.
import { createStyleObject } from '@capsizecss/core';

const capsizeStyles = createStyleObject({
  fontSize: 16,
  leading: 24,
  fontMetrics: {
    capHeight: 700,
    ascent: 1058,
    descent: -291,
    lineGap: 0,
    unitsPerEm: 1000,
  },
});

Note: It is recommended that you install the @capsizecss/metrics package and import the metrics from there:

import { createStyleObject } from '@capsizecss/core';
import arialMetrics from '@capsizecss/metrics/arial';

const capsizeStyles = createStyleObject({
  fontSize: 16,
  leading: 24,
  fontMetrics: arialMetrics,
});

See the fontMetrics option documented below for more ways to obtain these metrics.

  1. Apply styles to the text element, for example via the css prop.
<div
  css={{
    // fontFamily: '...' etc,
    ...capsizeStyles,
  }}
>
  My capsized text πŸ›Ά
</div>

createStyleString

Returns a CSS string that can be inserted into a style tag or appended to a stylesheet.

  1. Import createStyleString passing the relevant options.
import { createStyleString } from '@capsizecss/core';
import arialMetrics from '@capsizecss/metrics/arial';

const capsizedStyleRule = createStyleString('capsizedText', {
  fontSize: 16,
  leading: 24,
  fontMetrics: arialMetrics,
});
  1. Add the styles into a stylesheet or style element and apply the specified class name.
document.write(`
  <style type="text/css">
    ${capsizedStyleRule}
  </style>
  <div class="capsizedText">
    My capsized text πŸ›Ά
  </div>
`);

Options

Text size

Capsize supports two methods of defining the size of text, capHeight and fontSize.

NOTE: You should only ever pass one or the other, not both.

capHeight: <number>

Sets the height of the capital letters to the defined value. Defining typography in this way makes aligning to a grid or with other elements, e.g. icons, a breeze.

Highlighting the cap height

fontSize: <number>

Setting the font size allows you to get all the benefits of the white space trimming, while still specifying an explicit font-size for your text. This can be useful when needed to match a concrete design spec or fitting into an existing product.

Highlighting the font size

Line height

Capsize supports two mental models for specifying line height, lineGap and leading. If you pass neither the text will follow the default spacing of the specified font, e.g. line-height: normal.

NOTE: You should only ever pass one or the other, not both.

lineGap: <number>

Sets the number of pixels between lines, as measured between the baseline and cap height of the next line.

Highlighting the line gap

leading: <number>

Sets the line height to the provided value as measured from the baseline of the text. This aligns the web with how typography is treated in design tools.

Highlighting the leading

Font Metrics

This metadata is extracted from the metrics tables inside the font itself. There are a number of ways to find this information:

  • If using a Google Font or system font, install the @capsizecss/metrics package and import the metrics by name. For example:

    import arialMetrics from '@capsizecss/metrics/arial';
  • If using a font from a file, install the @capsizecss/unpack package and extract the metrics from the font file directly. For example:

    import { fromFile } from '@capsizecss/unpack';
    
    const metrics = await fromFile(filePath);
  • Or, use the Capsize website to find these by selecting a font and referencing Metrics tab in step 3.

Core

The core package also provides a few other metrics-based features for improving typography on the web:

createFontStack

Creates metrics-based @font-face declarations to improve the alignment of font family fallbacks, which can dramatically improve the Cumulative Layout Shift metric for sites that depend on a web font.

Usage

Consider the following example, where the desired web font is Lobster, falling back to Helvetica Neue and then Arial, e.g. font-family: Lobster, 'Helvetica Neue', Arial.

  1. Import createFontStack from the core package:
import { createFontStack } from '@capsizecss/core';
  1. Import the font metrics for each of the desired fonts (see Font Metrics above):
import lobster from '@capsizecss/metrics/lobster';
import helveticaNeue from '@capsizecss/metrics/helveticaNeue';
import arial from '@capsizecss/metrics/arial';
  1. Create your font stack passing the metrics as an array, using the same order as you would via the font-family CSS property.
const { fontFamily, fontFaces } = createFontStack([
  lobster,
  helveticaNeue,
  arial,
]);

The returned value contains the generated font face declarations as well as the computed fontFamily with the appropriately ordered font aliases.

Usage in CSS stylesheet or a style tag

The returned values can be templated into a stylesheet or a style block. Here is an example handlebars template:

<style type="text/css">
  .heading {
    font-family: {{ fontFamily }}
  }

  {{ fontFaces }}
</style>

This will produce the following CSS:

.heading {
  font-family: Lobster, 'Lobster Fallback: Helvetica Neue',
    'Lobster Fallback: Arial';
}

@font-face {
  font-family: 'Lobster Fallback: Helvetica Neue';
  src: local('Helvetica Neue');
  ascent-override: 115.1741%;
  descent-override: 28.7935%;
  size-adjust: 86.8251%;
}
@font-face {
  font-family: 'Lobster Fallback: Arial';
  src: local('Arial');
  ascent-override: 113.5679%;
  descent-override: 28.392%;
  size-adjust: 88.053%;
}

Usage with CSS-in-JS frameworks

If working with a CSS-in-JS library, the returned fontFaces can be provided as a JavaScript style object by providing styleObject as a fontFaceFormat option.

Here is an example using Emotion:

import { Global } from '@emotion/core';

const { fontFaces, fontFamily } = createFontStack(
  [lobster, helveticaNeue, arial],
  {
    fontFaceFormat: 'styleObject',
  },
);

export const App = () => (
  <>
    <Global styles={fontFaces} />
    <p css={{ fontFamily }}>...</p>
  </>
);

Also useful as a source for further manipulation given it is a data structure that can be iterated over or extended.

Providing additional font-face properties

Additional properties can be added to the generated @font-face declarations via the fontFaceProperties option:

const { fontFamily, fontFaces } = createFontStack(
  [lobster, helveticaNeue, arial],
  {
    fontFaceProperties: {
      fontDisplay: 'swap',
    },
  },
);

This will result in the following additions to the declarations:

 @font-face {
   font-family: 'Lobster Fallback: Helvetica Neue';
   src: local('Helvetica Neue');
   ascent-override: 115.1741%;
   descent-override: 28.7935%;
   size-adjust: 86.8251%;
+  font-display: swap;
 }
 @font-face {
   font-family: 'Lobster Fallback: Arial';
   src: local('Arial');
   ascent-override: 113.5679%;
   descent-override: 28.392%;
   size-adjust: 88.053%;
+  font-display: swap;
 }

Worth noting, passing any of the metric override CSS properties will be ignored as they are calculated by Capsize. However, the size-adjust property is accepted to support fine-tuning the override for particular use cases. This can be used to finesse the adjustment for specific text, or to disable the adjustment by setting it to 100%.

precomputeValues

Returns all the information required to create leading trim styles for a specific font size given the provided font metrics. This is useful for integrations with different styling solutions.

Accepts the same options as createStyleObject and createStyleString.

import { precomputeValues } from '@capsizecss/core';
import arialMetrics from '@capsizecss/metrics/arial';

const capsizeValues = precomputeValues({
  fontSize: 16,
  leading: 24,
  fontMetrics: arialMetrics,
});

// => {
//  fontSize: string,
//  lineHeight: string,
//  capHeightTrim: string,
//  baselineTrim: string,
//}

getCapHeight

Return the rendered cap height for a specific font size given the provided font metrics.

import { getCapHeight } from '@capsizecss/core';
import arialMetrics from '@capsizecss/metrics/arial';

const actualCapHeight = getCapHeight({
  fontSize: 24,
  fontMetrics: arialMetrics,
});

// => number

Metrics

To make the retrieval of font metrics easy, Capsize provides the @capsizecss/metrics package containing all the required data for both system and Google fonts.

npm install @capsizecss/metrics

See the package for documentation.

Unpack

If you are using a custom font or one not included in the @capsizecss/metrics package, Capsize provides the @capsizecss/unpack package to extract the required data either via a URL or from a local file.

npm install @capsizecss/unpack

See the package for documentation.

Integrations

Thanks

License

MIT.

More Repositories

1

vanilla-extract

Zero-runtime Stylesheets-in-TypeScript
TypeScript
5,738
star
2

playroom

Design with JSX, powered by your own component library.
TypeScript
4,321
star
3

braid-design-system

Themeable design system for the SEEK Group
TypeScript
1,487
star
4

treat

🍬 Themeable, statically extracted CSS‑in‑JS with near‑zero runtime.
TypeScript
1,152
star
5

html-sketchapp-cli

Quickly generate Sketch libraries from HTML documents and living style guides, powered by html-sketchapp
JavaScript
633
star
6

sku

Front-end development toolkit
JavaScript
472
star
7

seek-style-guide

Living style guide for SEEK, powered by React, webpack, CSS Modules and Less.
JavaScript
309
star
8

serverless-haskell

Deploying Haskell applications to AWS Lambda with Serverless
Haskell
213
star
9

css-modules-typescript-loader

Webpack loader to create TypeScript declarations for CSS Modules
JavaScript
193
star
10

vocab

Vocab is a strongly typed internationalization framework for React
TypeScript
125
star
11

csp-server

CSP (Content Security Policy) reports server which forwards reports to Elasticsearch.
JavaScript
57
star
12

docker-ecr-cache-buildkite-plugin

Zero config plugin for caching Docker images in Amazon ECR or Google Container Registry
Shell
51
star
13

skuba

🀿 SEEK development toolkit for backend applications and packages
TypeScript
48
star
14

aws-sm-buildkite-plugin

Buildkite plugin for working with AWS Secrets Manager
Shell
42
star
15

listo

Listo. Use questionnaires and checklists to make it easy to do the right thing, regarding the software you build.
TypeScript
27
star
16

crackle

A build tool for apps and packages, static and server-rendered sites
TypeScript
25
star
17

github-merged-pr-buildkite-plugin

BuildKite plugin to work with GitHub PRs
Shell
25
star
18

changesets-snapshot

A GitHub Action for publishing snapshot releases when using changesets
TypeScript
18
star
19

fsharp-workshop

Exercises for an F# workshop.
F#
15
star
20

lightgbm4j

A JVM interface 🌯 for LightGBM, written in Scala, for inference in production.
Scala
14
star
21

is-pwned

is-pwned β€”Β Utility to safely check the HaveIBeenPwned "Pwned Passwords" database in the browser.
TypeScript
12
star
22

docker-ecr-publish-buildkite-plugin

Build, tag, and push Docker images to Amazon ECR
Shell
11
star
23

seek-style-guide-webpack

Webpack decorators for integrating with the SEEK Style Guide.
JavaScript
11
star
24

react-scrollmonitor

React wrapper for scrollMonitor
JavaScript
11
star
25

gradle-aws-plugin

AWS Plugin for Gradle
Scala
10
star
26

evaporate

Evaporate is a convention-based, simple CloudFormation Stack deployment tool.
Haskell
9
star
27

browserslist-config-seek

Shareable Browserslist config for SEEK
JavaScript
9
star
28

seek.automation.phantom

A Pact based service simulator.
C#
9
star
29

toolbox

Standard build tools
Shell
8
star
30

aec

AWS EC2 CLI - easily work with ec2 instances via the cli 🐢
Python
8
star
31

create-ecr-buildkite-plugin

Create and manage an Amazon ECR repository
Shell
7
star
32

seek.automation.stub

A Pact based stubbing library for .NET.
C#
7
star
33

dynamotools

Tools to manage DynamoDB tables.
Go
7
star
34

snyk-buildkite-plugin

Buildkite plugin for running Snyk scans
Python
7
star
35

renovate-config-seek

Shareable Renovate config for SEEK
JavaScript
7
star
36

eslint-config-seek

Shareable ESLint configuration used by SEEK
JavaScript
7
star
37

private-npm-buildkite-plugin

A Buildkite plugin to simplify the use of an NPM token to install private modules
Shell
6
star
38

seek-stackable

iOS framework for laying out nested views vertically and horizontally.
Swift
5
star
39

datadog-event-buildkite-plugin

BuildKite plugin to send a deployment event to datadog
Shell
5
star
40

ensure-gitignore

Ensure the presence of patterns within a project's gitignore
JavaScript
5
star
41

https-proxy-server

HTTP proxy server in Node.js allowing modification of user responses.
JavaScript
4
star
42

style-guide-resources-for-sketch

A template containing SEEK UI components, for designers using Sketch.
4
star
43

scoobie

🧢 Component library for SEEK documentation sites
TypeScript
4
star
44

ssm-buildkite-plugin

Secure Store Parameters for Buildkite
Shell
4
star
45

wingman

πŸ›© Reference implementation of a SEEK-integrated recruitment system
TypeScript
4
star
46

koala

🐨 Koa add-ons for SEEK-standard tracing, logging and metrics
TypeScript
4
star
47

nodejs-consumer-pact-interceptor

A Node.js consumer Pact tool.
JavaScript
3
star
48

aws-lambda-scala

Example of an AWS Lambda function written in Scala with deployment tools
Scala
3
star
49

rynovate

🦏 dangerouslySetRenovatePreset
3
star
50

commitlint-config-seek

Shareable commitlint config for SEEK
JavaScript
3
star
51

kpt-functions

A library of Kpt functions for extending Kpt's functionality
Go
3
star
52

ad-posting-api-client

SEEK's Job Ad Posting API .NET client and sample consumer code.
C#
2
star
53

IdentityServer4.Contrib.DynamoDB

A persistence layer using DynamoDB for operational data for Identity Server 4
C#
2
star
54

serverless-plugin-inspect

Serverless plugin - Get AWS stack info in JSON.
JavaScript
2
star
55

datadog-custom-metrics

🐢 Common interface for sending Datadog custom metrics from Node.js runtime environments
TypeScript
1
star
56

text1

A NonEmpty version of Data.Text
Haskell
1
star
57

skuba-dive

🌊 Minimal runtime for skuba
TypeScript
1
star
58

logger

TypeScript
1
star
59

fake-hr

Node.js package of HR data sets for mocking and testing
TypeScript
1
star
60

tslint-config-seek

TSLint configuration used by SEEK
JavaScript
1
star
61

action-project-manager

A github action which labels and adds isses and PRs to github projects
JavaScript
1
star
62

babel-plugin-seek-style-guide

Optimise your bundle by automatically rewriting import statements from seek-style-guide
JavaScript
1
star
63

splunk-logger

Generates Splunk consumable logs in Node JS 4.3.2 AWS Lambda functions.
JavaScript
1
star
64

redux-batched-subscribe

FORK: https://github.com/tappleby/redux-batched-subscribe
JavaScript
1
star
65

spark-dist

Spark with hadoop-aws 3.1 for modern S3 access
Makefile
1
star