units – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Thu, 15 Apr 2021 15:43:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 units – CSS-Tricks https://css-tricks.com 32 32 45537868 Platform News: Rounded Outlines, GPU-Accelerated SVG Animations, How CSS Variables Are Resolved https://css-tricks.com/platform-news-rounded-outlines-gpu-accelerated-svg-animations-how-css-variables-are-resolved/ https://css-tricks.com/platform-news-rounded-outlines-gpu-accelerated-svg-animations-how-css-variables-are-resolved/#comments Fri, 02 Apr 2021 19:35:28 +0000 https://css-tricks.com/?p=337636 In the news this week, Firefox gets rounded outlines, SVG animations are now GPU-accelerated in Chrome, there are no physical units in CSS, The New York Times crossword is accessible, and CSS variables are resolved before the value is inherited.…


Platform News: Rounded Outlines, GPU-Accelerated SVG Animations, How CSS Variables Are Resolved originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
In the news this week, Firefox gets rounded outlines, SVG animations are now GPU-accelerated in Chrome, there are no physical units in CSS, The New York Times crossword is accessible, and CSS variables are resolved before the value is inherited.

Let’s jump in the news!

Rounded outlines are coming to Firefox

The idea to have the outline follow the border curve has existed ever since it became possible to create rounded borders via the border-radius property in the mid 2000s. It was suggested to Mozilla, WebKit, and Chromium over ten years ago, and it’s even been part of the CSS UI specification since 2015:

The parts of the outline are not required to be rectangular. To the extent that the outline follows the border edge, it should follow the border-radius curve.

Fast-forward to today in 2021 and outlines are still rectangles in every browser without exception:

But this is finally starting to change. In a few weeks, Firefox will become the first browser with rounded outlines that automatically follow the border shape. This will also apply to Firefox’s default focus outline on buttons.

Three sets of round yellow buttons, comparing how Chrome, Firefox, and Safari handle outlines.

Please star Chromium Issue #81556 (sign in required) to help prioritize this bug and bring rounded outlines to Chrome sooner rather than later.

SVG animations are now GPU-accelerated in Chrome

Until recently, animating an SVG element via CSS would trigger repaint on every frame (usually 60 times per second) in Chromium-based browsers. Such constant repainting can have a negative impact on the smoothness of the animation and the performance of the page itself.

The latest version of Chrome has eliminated this performance issue by enabling hardware acceleration for SVG animations. This means that SVG animations are offloaded to the GPU and no longer run on the main thread.

Side by side comparison of the Performance tab in Chrome DevTools.
In this example, the SVG circle is continuously faded in and out via a CSS animation (see code)

The switch to GPU acceleration automatically made SVG animations more performant in Chromium-based browsers (Firefox does this too), which is definitely good news for the web:

Hooray for more screen reader-accessible, progressively enhanced SVG animations and less Canvas.

There cannot be real physical units in CSS

CSS defines six physical units, including in (inches) and cm (centimeters). Every physical unit is in a fixed ratio with the pixel unit, which is the canonical unit. For example, 1in is always exactly 96px. On most modern screens, this length does not correspond to 1 real-world inch.

The FAQ page of the CSS Working Group now answers the question why there can’t be real physical units in CSS. In short, the browser cannot always determine the exact size and resolution of the display (think projectors). For websites that need accurate real-world units, the Working Group recommends per-device calibration:

Have a calibration page, where you ask the user to measure the distance between two lines that are some CSS distance apart (say, 10cm), and input the value they get. Use this to find the scaling factor necessary for that screen (CSS length divided by user-provided length).

This scaling factor can then be set to a custom property and used to compute accurate lengths in CSS:

html {
  --unit-scale: 1.428;
}

.box {
  /* 5 real-world centimeters */
  width: calc(5cm * var(--unit-scale, 1));
}

The Times crossword is accessible to screen reader users

The NYT Open team wrote about some of the improvements to the New York Times website that have made it more accessible in recent years. The website uses semantic HTML (<article>, <nav>, etc.), increased contrast on important components (e.g., login and registration), and skip-to-content links that adapt to the site’s paywall.

Furthermore, the Games team made the daily crossword puzzle accessible to keyboard and screen reader users. The crossword is implemented as a grid of SVG <rect> elements. As the user navigates through the puzzle, the current square’s aria-label attribute (accessible name) is dynamically updated to provide additional context.

Screenshot of the crossword game with an open screen reader dialog announcing what is on the screen.
The screen reader announces the clue, the number of letters in the solution, and the position of the selected square

You can play the mini crossword without an account. Try solving the puzzle with the keyboard.

CSS variables are resolved before the value is inherited

Yuan Chuan recently shared a little CSS quiz that I didn’t answer correctly because I wasn’t sure if a CSS variable (the var() function) is resolved before or after the value is inherited. I’ll try to explain how this works on the following example:

html {
  --text-color: var(--main-color, black);
}

footer {
  --main-color: brown;
}

p {
  color: var(--text-color);
}

The question: Is the color of the paragraph in the footer black or brown? There are two possibilities. Either (A) the declared values of both custom properties are inherited to the paragraph, and then the color property resolves to brown, or (B) the --text-color property resolves to black directly on the <html> element, and then this value is inherited to the paragraph and assigned to the color property.

Two CSS rulesets, one as Option A and the other as Option B, both showing how variables are inherited and resolved between elements.

The correct answer is option B (the color is black). CSS variables are resolved before the value is inherited. In this case, --text-color falls back to black because --main-color does not exist on the <html> element. This rule is specified in the CSS Variables module:

It is important to note that custom properties resolve any var() functions in their values at computed-value time, which occurs before the value is inherited.


Platform News: Rounded Outlines, GPU-Accelerated SVG Animations, How CSS Variables Are Resolved originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/platform-news-rounded-outlines-gpu-accelerated-svg-animations-how-css-variables-are-resolved/feed/ 4 337636
What does 100% mean in CSS? https://css-tricks.com/what-does-100-mean-in-css/ https://css-tricks.com/what-does-100-mean-in-css/#comments Fri, 07 Aug 2020 19:08:32 +0000 https://css-tricks.com/?p=318815 When using percentage values in CSS like this…

.element {
  margin-top: 40%;
}

…what does that % value mean here? What is it a percentage of? There’ve been so many times when I’ll be using percentages and something weird happens. …


What does 100% mean in CSS? originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
When using percentage values in CSS like this…

.element {
  margin-top: 40%;
}

…what does that % value mean here? What is it a percentage of? There’ve been so many times when I’ll be using percentages and something weird happens. I typically shrug, change the value to something else and move on with my day.

But Amelia Wattenberger says no! in this remarkable deep dive into how percentages work in CSS and all the peculiar things we need to know about them. And as is par for the course at this point, any post by Amelia has a ton of wonderful demos that perfectly describe how the CSS in any given example works. And this post is no different.

To Shared LinkPermalink on CSS-Tricks


What does 100% mean in CSS? originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/what-does-100-mean-in-css/feed/ 1 318815
Turning a Fixed-Size Object into a Responsive Element https://css-tricks.com/turning-a-fixed-size-object-into-a-responsive-element/ https://css-tricks.com/turning-a-fixed-size-object-into-a-responsive-element/#comments Mon, 11 May 2020 14:46:21 +0000 https://css-tricks.com/?p=308201 I was in a situation recently where I wanted to show an iPhone on a website. I wanted users to be able to interact with an application demo on this “mock” phone, so it had to be rendered in CSS, …


Turning a Fixed-Size Object into a Responsive Element originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
I was in a situation recently where I wanted to show an iPhone on a website. I wanted users to be able to interact with an application demo on this “mock” phone, so it had to be rendered in CSS, not an image. I found a great library called marvelapp/devices.css. The library implemented the device I needed with pure CSS, and they looked great, but there was a problem: the devices it offered were not responsive (i.e. they couldn’t be scaled). An open issue listed a few options, but each had browser incompatibilities or other issues. I set out to modify the library to make the devices responsive.

Here is the final resizable library. Below, we’ll walk through the code involved in creating it.

The original library was written in Sass and implements the devices using elements with fixed sizing in pixels. The authors also provided a straightforward HTML example for each device, including the iPhone X we’ll be working with throughout this article. Here’s a look at the original. Note that the device it renders, while detailed, is rather large and does not change sizes.

Here’s the approach

There are three CSS tricks that I used to make the devices resizable:

  1. calc(), a CSS function that can perform calculations, even when inputs have different units
  2. --size-divisor, a CSS custom property used with the var() function
  3. @media queries separated by min-width

Let’s take a look at each of them.

calc()

The CSS calc() function allows us to change the size of the various aspects of the device. The function takes an expression as an input and returns the evaluation of the function as the output, with appropriate units. If we wanted to make the devices half of their original size, we would need to divide every pixel measurement by 2.

Before:

width: 375px;

After:

width: calc(375px / 2);

The second snippet yields a length half the size of the first snippet. Every pixel measurement in the original library will need to be wrapped in a calc() function for this to resize the whole device.

var(–size-divisor)

A CSS variable must first be declared at the beginning of the file before it can be used anywhere.

:root {
  --size-divisor: 3;
}

With that, this value is accessible throughout the stylesheet with the var() function. This will be exceedingly useful as we will want all pixel counts to be divided by the same number when resizing devices, while avoiding magic numbers and simplifying the code needed to make the devices responsive.

width: calc(375px / var(--size-divisor));

With the value defined above, this would return the original width divided by three, in pixels.

@media

To make the devices responsive, they must respond to changes in screen size. We achieve this using media queries. These queries watch the width of the screen and fire if the screen size crosses given thresholds. I chose the breakpoints based on Bootstrap’s sizes for xs, sm, and so on

There is no need to set a breakpoint at a minimum width of zero pixels; instead, the :root declaration at the beginning of the file handles these extra-small screens. These media queries must go at the end of the document and be arranged in ascending order of min-width.

@media (min-width: 576px) {
  :root {
    --size-divisor: 2;
  }
}
@media (min-width: 768px) {
  :root {
    --size-divisor: 1.5;
  }
}
@media (min-width: 992px) { 
  :root {
    --size-divisor: 1;
  }
}
@media (min-width: 1200px) { 
  :root {
    --size-divisor: .67;
  }
}

Changing the values in these queries will adjust the magnitude of resizing that the device undergoes. Note that calc() handles floats just as well as integers.

Preprocessing the preprocessor with Python

With these tools in hand, I needed a way to apply my new approach to the multi-thousand-line library. The resulting file will start with a variable declaration, include the entire library with each pixel measurement wrapped in a calc() function, and end with the above media queries.

Rather than prepare the changes by hand, I created a Python script that automatically converts all of the pixel measurements.

def scale(token):
  if token[-2:] == ';\n':
    return 'calc(' + token[:-2] + ' / var(--size-divisor));\n'
  elif token[-3:] == ');\n':
    return '(' + token[:-3] + ' / var(--size-divisor));\n'
  return 'calc(' + token + ' / var(--size-divisor))'

This function, given a string containing NNpx, returns calc(NNpx / var(--size-divisor));. Throughout the file, there are fortunately only three matches for pixels: NNpx, NNpx; and NNpx);. The rest is just string concatenation. However, these tokens have already been generated by separating each line by space characters.

def build_file(scss):
  out = ':root {\n\t--size-divisor: 3;\n}\n\n'
  for line in scss:
    tokens = line.split(' ')
    for i in range(len(tokens)):
      if 'px' in tokens[i]:
        tokens[i] = scale(tokens[i])
    out += ' '.join(tokens)
  out += "@media (min-width: 576px) {\n  \
    :root {\n\t--size-divisor: 2;\n  \
    }\n}\n\n@media (min-width: 768px) {\n \
    :root {\n\t--size-divisor: 1.5;\n  \
    }\n}\n\n@media (min-width: 992px) { \
    \n  :root {\n\t--size-divisor: 1;\n  \
    }\n}\n\n@media (min-width: 1200px) { \
    \n  :root {\n\t--size-divisor: .67;\n  }\n}"
  return out

This function, which builds the new library, begins by declaring the CSS variable. Then, it iterates through the entire old library in search of pixel measurements to scale. For each of the hundreds of tokens it finds that contain px, it scales that token. As the iteration progresses, the function preserves the original line structure by rejoining the tokens. Finally, it appends the necessary media queries and returns the entire library as a string. A bit of code to run the functions and read and write from files finishes the job.

if __name__ == '__main__':
  f = open('devices_old.scss', 'r')
  scss = f.readlines()
  f.close()
  out = build_file(scss)
  f = open('devices_new.scss', 'w')
  f.write(out)
  f.close()

This process creates a new library in Sass. To create the CSS file for final use, run:

sass devices_new.scss devices.css

This new library offers the same devices, but they are responsive! Here it is:

To read the actual output file, which is thousands of lines, check it out on GitHub.

Other approaches

While the results of this process are pretty compelling, it was a bit of work to get them. Why didn’t I take a simpler approach? Here are three more approaches with their advantages and drawbacks.

zoom

One initially promising approach would be to use zoom to scale the devices. This would uniformly scale the device and could be paired with media queries as with my solution, but would function without the troublesome calc() and variable.

This won’t work for a simple reason: zoom is a non-standard property. Among other limitations, it is not supported in Firefox.

Replace px with em

Another find-and-replace approach prescribes replacing all instances of px with em. Then, the devices shrink and grow according to font size. However, getting them small enough to fit on a mobile display may require minuscule font sizes, smaller than the minimum sizes browsers, like Chrome, enforce. This approach could also run into trouble if a visitor to your website is using assistive technology that increases font size.

This could be addressed by scaling all of the values down by a factor of 100 and then applying standard font sizes. However, that requires just as much preprocessing as this article’s approach, and I think it is more elegant to perform these calculations directly rather than manipulate font sizes.

scale()

The scale() function can change the size of entire objects. The function returns a <transform-function>, which can be given to a transform attribute in a style. Overall, this is a strong approach, but does not change the actual measurement of the CSS device. I prefer my approach, especially when working with complex UI elements rendered on the device’s “screen.”

Chris Coyier prepared an example using this approach.

In conclusion

Hundreds of calc() calls might not be the first tool I would reach for if implementing this library from scratch, but overall, this is an effective approach for making existing libraries resizable. Adding variables and media queries makes the objects responsive. Should the underlying library be updated, the Python script would be able to process these changes into a new version of our responsive library.


Turning a Fixed-Size Object into a Responsive Element originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/turning-a-fixed-size-object-into-a-responsive-element/feed/ 3 308201
`lh` and `rlh` units https://css-tricks.com/lh-and-rlh-units/ https://css-tricks.com/lh-and-rlh-units/#comments Tue, 05 May 2020 18:22:23 +0000 https://css-tricks.com/?p=308061 There’s some new units I was totally unaware of from the Level 4 spec for CSS values! The lh unit is “equal to the computed value of line-height” and rlh is the same only of the root element …


`lh` and `rlh` units originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
There’s some new units I was totally unaware of from the Level 4 spec for CSS values! The lh unit is “equal to the computed value of line-height” and rlh is the same only of the root element (probably the <html> element) rather than the current element.

Why would that be useful? Šime Vidas’ has a strong point:

“Vertical Inline Centering” of an icon
.inline-icon {
  display: inline-block;
  width: 1lh;
  height: 1lh;
}

`lh` and `rlh` units originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/lh-and-rlh-units/feed/ 5 308061
Designing An Aspect Ratio Unit For CSS https://css-tricks.com/designing-an-aspect-ratio-unit-for-css/ https://css-tricks.com/designing-an-aspect-ratio-unit-for-css/#comments Wed, 13 Mar 2019 14:29:11 +0000 http://css-tricks.com/?p=284424 Rachel Andrew says that the CSS Working Group designed an aspect ratio unit at a recent meeting. The idea is to find an elegant solution to those times when we want the height of an element to be calculated in …


Designing An Aspect Ratio Unit For CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Rachel Andrew says that the CSS Working Group designed an aspect ratio unit at a recent meeting. The idea is to find an elegant solution to those times when we want the height of an element to be calculated in response to the width of the element, or vice versa.

Say, for example, we have a grid layout with a row of elements that should maintain a square (1:1) ratio. There are a few existing, but less-than-ideal ways we can go:

  • Define one explicit dimension. If we define the height of the items in the grid but use an intrinsic value on the template columns (e.g. auto-fill), then we no longer know the width of the element as the container responds to the browser viewport. The elements will grow and squish but never maintain that perfect square.
  • Define explicit dimensions. Sure, we can tell an element to be 200px wide and 200px tall, but what happens when more content is added to an item than there is space? Now we have an overflow problem.
  • Use the padding hack. The block-level (top-to-bottom) padding percentage of an element is calculated by the element’s inline width and we can use that to calculate height. But, as Rachel suggests, it’s totally un-intuitive and tough to maintain.

Chris wrote up a full rundown of possible ways to maintain aspect ratio, but none of them are as elegant as CSS Working Group’s proposed solution:

.box {
  width: 400px;
  height: auto;
  aspect-ratio: 1/1;
}

See that? An aspect-ratio property with an aspect ratio unit would calculate the height of the element based on the value of the width property.

Or, in the case of a grid layout where the columns are set to auto-fill:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

.item {
  aspect-ratio: 1/1;
}

Very cool! But where does the proposal go from here? The aspect-ratio is included in the rough draft of the CSS Sizing 4 specification. Create an issue in the CSSWG GitHub repo if you have ideas or suggestions. Or, as Rachel suggests, comment on her Smashing Magazine post or even write up your own post and send it along. This is a great chance to add your voice to a possible new feature.

To Shared LinkPermalink on CSS-Tricks


Designing An Aspect Ratio Unit For CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/designing-an-aspect-ratio-unit-for-css/feed/ 1 284424
Gradians and Turns: the quiet heroes of CSS angles https://css-tricks.com/gradians-and-turns-the-quiet-heroes-of-css-angles/ Wed, 06 Feb 2019 15:34:36 +0000 http://css-tricks.com/?p=282291 I love coming across little overlooked CSS gems, like the gradien (grad) and turn (turn) units that Ken Bellows uncovers in his post explaining them. I don’t know, maybe y’all are already aware of them, but …


Gradians and Turns: the quiet heroes of CSS angles originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
I love coming across little overlooked CSS gems, like the gradien (grad) and turn (turn) units that Ken Bellows uncovers in his post explaining them. I don’t know, maybe y’all are already aware of them, but they’re certainly new to me.

They’re additional options for dealing with angles, where degrees (deg) and radians (rad) are more commonly known. I’m partial to degrees anytime I’m working with rotations. But now that I know there’s an easier way to express a half rotation by using 0.5turn instead of 180deg, I can see myself reaching for turns much more often.

When you’re designing an animation or thinking about how to add some rotation to your design, how are you thinking about it? You probably aren’t thinking in numbers. … You don’t usually think in degrees or radians. You think in terms of full turns and portions of turns. At least, I do.

After looking at his table of comparisons, I take the point:

Degrees Radians Gradians Turns My Fav Unit
30deg 0.52rad 33.33grad 0.08turn Gradians
45deg 0.79rad 50grad 0.13turn Gradians
60deg 1.04rad 66.67grad 0.17turn Gradians
90deg 1.57rad 100grad 0.25turn Turns
180deg 3.14rad 200grad 0.5turn Turns
360deg 6.28rad 400grad 1turn Turns
720deg 12.56rad 800grad 2turn Turns
1080deg 25.12rad 1200grad 3turn Turns

Hear, hear! And since these units are supported back to IE 9, seems like something fun to try out.

(Hat tip to Rachel Andrew for sharing this in her awesome CSS Layout News email.)

To Shared LinkPermalink on CSS-Tricks


Gradians and Turns: the quiet heroes of CSS angles originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
282291
The Lengths of CSS https://css-tricks.com/the-lengths-of-css/ https://css-tricks.com/the-lengths-of-css/#comments Wed, 13 Mar 2013 18:25:33 +0000 http://css-tricks.com/?p=20529 There are quite a few properties in CSS that take a length as a value. The box model properties are the obvious ones: width, height, margin, padding, border. But plenty of others as well: the …


The Lengths of CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
There are quite a few properties in CSS that take a length as a value. The box model properties are the obvious ones: width, height, margin, padding, border. But plenty of others as well: the offset and sizing of a box-shadow or the size and spacing of fonts. What are all the accepted “length” properties in CSS? There are quite a few.

The Absolute Lengths

px

.wrap {
  width: 400px; 
}

Pixels don’t have anything to do with the literal screen pixels in the display you are looking at. It’s actually an angular measurement.

Nerdy bits about what pixels are in CSS

Pixels in CSS are anchored to the CSS reference pixel which is the visual angle of one pixel, 0.0213 degrees or 1.278 minutes of arc. This is based on a device with a pixel density of 96 DPI and a distance from the reader of an arm’s length of 28 inches. Device manufacturers can thus use the reference pixel to set a size based on intended/expected visual distance.

It is supposed to be a value that is normalized across devices and displays, but that increasingly isn’t true anymore. For instance, websites on the iPad mini render the same as on the iPad, meaning if those values were set in pixels that normalization is rather out the window.

Pixels are still a canonical measurement on the web though as they are consistently handled, many other lengths map directly to pixels, and JavaScript speaks in pixels.

in

.wrap {
  width: 4in; 
}

Inches are a physical measurement, but in CSS land, they just map directly to pixels. Feel free to chime in with use cases in the comments and I’ll add them here, but I have never seen a practical use case for this or the rest of these physical measurements.

1in == 96px

cm

.wrap {
  width: 20cm; 
}

For most of the world, centimeters are more familiar and useful as a physical measurement. They also just map to pixels:

1cm == 37.8px

mm

.wrap {
  width: 200mm; 
}

And an order of magnitude smaller…

1mm == 0.1cm == 3.78px

The Font-Relative Lengths

Em

.wrap {
  width: 40em; 
}

A relative unit. Originally a typographic measurement based on the current typefaces capital letter “M”. Although the length doesn’t change when you change font-family, it does change when you change the font-size.

Without any CSS at all, 1em would be:

1em == 16px == 0.17in == 12pt == 1pc == 4.2mm == 0.42cm

If any CSS changes the font size (at any level in the document), 1em becomes whatever the new font-size is.

Making things a tiny bit funkier, em units multiply upon themselves when applied to font-size, so if an element with font-size 1.1em is within an element with font-size 1.1em within yet another element with font-size 1.1em, the resulting size is 1.1 ✕ 1.1 ✕ 1.1 == 1.331rem (root em). Meaning even if an element is set to, say 10em, that doesn’t mean it will be a consistent width everywhere it appears. It could be wider or narrower if the font-size changes (see proof).

Rem

.wrap {
  width: 40rem; 
}

A relative unit, like em, but it is always relative to the “root” element (i.e. :root {}) rather than using the cascade, like em does. This vastly simplifies working with relative units.

Notable browser support issues: doesn’t work in IE 8, Safari 4, or iOS 3.2.

Points

.wrap {
  width: 120pt; 
}

A point is a physical measurement equal to 1/72 of an inch. Points are the most common way to size type outside of CSS (likely why it is supported in CSS). It’s still common in language “Of course they set this important information in tiny eight-point type!”.

Points make the most sense in print stylesheets for sizing type, where physical media is involved, but there is nothing preventing you from using pt for screen media or anywhere else a length is accepted.

Notable browser support issues: There used to be big differences in on-screen rendering of pt size. Here’s a comparison of IE 6 vs Firefox (probably 3.6).

Pica

.wrap {
  width: 12pc; 
}

The same story as points, only 1pc == 12pt.

ex

.wrap {
  width: 60ex;
}

This is a measurement based on the x-height of the current font. Sometimes that comes from information embedded in the font itself, sometimes browsers figure it out by measuring a lower case glyph, and worst case, it’s set to 0.5em. It is named “x” height because it is supposedly based on the height of the x character. To understand x-height, think of a lowercase character that as a bit that sticks up (ascender) like a lowercase “d”. The x-height doesn’t include that ascender, it is the height of the lower loop part of that character.

Unlike ems, which don’t change when you change the font-family, ex units do change when you change the font-family, as the value of one unit is specifically bound to that font. (proof).

ch

.wrap {
  width: 60ch;
}

This is similar in spirit to x-height, only ch is based on the width of the zero (0) character instead of the height of the x character. It also changes as the font-family changes.

The Viewport Percentage Lengths

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
261911166.1

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
1081074.48

vw

.wrap {
  width: 10vw;
}

This is the “viewport width” unit. 1vw is equal to 1% of the width of the viewport. It is similar to percentage, except that the value remains consistent for all elements regardless of their parent elements or parent elements width. A bit like how rem units are always relative to the root.

Sizing type is the major use case here. See Viewport Sized Typography.

Notable browser support issues: No support in any mobile browsers except the very latest iOS 6. This goes for all the viewport related length units.

vh

.wrap {
  width: 10vh;
}

This is the same as the vw (viewport width) unit only it is based on the viewport height instead.

vmin

.wrap {
  width: 20vmin;
}

This value will be whichever is smaller at the moment, vw or vh. In the standard use case of sizing type, this may be a more useful metric than vw or vh on their own in determining true screen size.

vmax

.wrap {
  width: 20vmax;
}

This value will be whichever is larger at the moment, vw or vh.

Notable browser support issues: WebKit based browsers support vmin but not vmax (yet). Firefox does support vmax though.

Odd Ball Out

Percentage

.wrap {
  width: 50%; 
}

A length set in percentage is based on the length of the same property of the parent element. For example, if an element renders at 450px width, a child element with a width set to 50% will render at 225px1.

Trivia: percentage isn’t technically a length unit, but I’m including it here since it is so related.

More Information

What is supported in your browser?

See here:

Check out this Pen!

1 Assuming the child element isn’t inline-level or a table cell with some weird table-y stuff going on, or a flex child or grid cell or any other fancy wacky stuff.


The Lengths of CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-lengths-of-css/feed/ 70 20529