Tag: Model

AR, VR, and a Model for 3D in HTML

Tucked down somewhere in the Safari Technology Preview 161 release notes is a seemingly innocous line about support for a new HTML element and attribute:

Added support for <model src> and honor <source type> attributes (257518@main)

Anytime I see mention of some element I don’t recognize, my mind goes straight to Huh! New to me, but probably old news for everyone else. It’s poor posture, I know, as it could just as easily be:

  • Hmm, looks like some propriatary experiment.
  • Wow, a truly new thing!

Truth is, it’s sorta all three.

It’s an evolving concept

As in, the first somewhat official-sounding thing I found on <model> wasn’t in the W3C spec but in WebKit’s repo for explainers. All that’s in the README is a giant note from 2021 that “The <model> element has moved to the Immersive Web CG.” I was about to hop over but my eye caught the HistoryAndEvolution.md file which has a nice rundown of early context on the <model> concept:

The <model> element was born out of a desire to take the next step and improve the experience of Safari’s integration with iOS’s AR Quick Look feature.

I had to look at Apple’s splash page for AR Quick Look. You know the new feature that some stores have where you can transpose a 3D rendering of a product in your own home using your phone camera? That’s the sort of stuff we’re talking about, and Apple links up a nice case study from the Metropolitan Museum of Art.

As I understand it from this limited context:

  • Drop a <model> element in the document.
  • Add an external source file, e.g. <model src="assets/example.usdz">.

The original proposal is from the Immersive Web Committee Group

That’s the team looking make Virtual Reality (VR) and Augmented Reality (AR) part of the web. Apple linked up their repo, so I made the jump and went straight to the explainer. This isn’t the spec or anything, but the original proposal. A much better definition of the element!

HTML allows the display of many media types through elements such as <img><picture>, or <video>, but it does not provide a declarative manner to directly display 3D content. Embedding 3D content within a page is comparatively cumbersome and relies on scripting the <canvas> element. We believe it is time to put 3D models on equal footing with other, already supported, media types.

[…]

The HTML <model> element aims to allow a website to embed interactive 3D models as conveniently as any other visual media. Models are expected to be created by 3D authoring tools or generated dynamically, but served as a standalone resource by the server.

The basic example pulls this together. It really does feel like the <video> or <picture> elements:

<model style="width: 400px; height: 300px">   <source src="assets/example.usdz" type="model/vnd.usdz+zip">   <source src="assets/example.glb" type="model/gltf-binary"> </model>

.usdz? .glb? Not the type of files that typically cross my desk. Guess I’ll need to brush up on those and any other file types that <model> might support. Again, all of this is merely the original proposal.

The draft proposal isn’t stubbed out quite yet

But it does provide a nice outline of where things could possibly go:

  • Adding a model to a document
  • Enabling interactivity
  • Supporting multiple formats
  • Providing fallback content
  • Making it accessible

There’s a lot to figure out. Most of what’s there are documented issues that need addressing. It does, however, shed more light on <model> like proposed attributes that make it feel even more like <video> such as autoplay, controls, loop, muted, poster, etc.

It goes back even further

The very earliest mention of 3D modeling I found was Keith Clark’s 2018 post in which he prototypes a custom element called <x-model>. He describes it as “a placeholder that provides access to the DOM and CSSOM” where the loading and rendering is done in three.js.

Keith’s idea is followed by the <model-viewer> component Joe Medley shared in 2020 (and a subsequent update to it). There’s even a homepage for it and it’s fun to drag Neil Armstrong around in space.

It’s possibly just an experiment?

I mean, the draft spec hasn’t been fleshed out. Apple seems willing to play ball thanks to the Safari TP 161 announcement. That makes total sense given how bullish Apple is on AR as a whole. (Apple Glasses, anyone?)

Google seems to have its foot in the door, albeit on the Web Components side of things. It’s easy to see how there may be a conflict of interest between what Apple and Google want from AR on the web.


These are all just my notes from trying to grok everything. There’s gotta be a lot more nuance to it than what little I know about it so far. I’m sure someone smarter can tie neater bow around <model> in the comments. 😉

And while we’re talking Safari Technology Preview, 162 just released the other day and it enables CSS nesting and the CSS relative color syntax.


AR, VR, and a Model for 3D in HTML originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS-Tricks

,

The Typed Object Model

I help write technical documentation and one feature I’ve been writing about this year that has really stood out is the Typed Object Model (or Typed OM). If you haven’t come across it yet you would be forgiven as it’s pretty new. It falls under the CSS Houdini suite of API’s and on the surface seems the least exciting. However, it underpins all of them and will eventually change how we view CSS as a language.

It allows for typing of values in CSS. Remember the base syntax of CSS:

selector {   property: value; }

That value can be a lot of things, colors, units, images, words. Which to CSS makes sense, but to us, when we access it and try to change it via any means, it comes as a string.

Typed OM allows that to be returned as a type instead. So if we were to access, say 10px in JavaScript, instead of '10px' being returned, we get the number 10 and the unit 'px'. Which is a whole heap easier to work with.

You may have seen some of Ana Tudor’s amazing demos. In her example ‘Hollow’, she registers custom properties in JavaScript to use in her CSS. She’s using the Properties & Values API and thus can determine the types of these properties. This wouldn’t be possible if Typed OM wasn’t around.

How about an example

On the face of it, it seems a little bit more work than the way we’re used to accessing and setting styles at the moment, but there are a lot of benefits. If we want to, say, get the width of an element we would do something like this:

const elementWidth = getComputedStyle(myElement).width; // returns '300px'

Not only are we accessing a string here, but getComputedStyle forces a re-layout. We may not be aware of what units are being used, and so accessing the numerical part of the string becomes tricky, and if we are running this in our code a number of times it could harm performance.

If we want to use Typed OM and return a typed value we would have to access the properties and values via computedStyleMap() and it’s get() method:

const elementWidth = myElement.computedStyleMap().get('width'); // returns CSSUnitValue {value: 300, type: 'px'}

Now we can access the value and the unit separately, and the value here is returned as an integer.

elementWidth.value // 300 elementWidth.unit // 'px'

We also haven’t forced a re-layout, which is nothing short of a win. Bet you’re now wondering and yes, not only can you access the CSS value as a type, but you can create unit values pretty easily as well, via the global CSS object:

let newWidth = CSS.px(320); // returns CSSUnitValue {value: 320, type: 'px'}

That’s a small example and one that’s easy to show, as the units part of the specification has been fleshed out somewhat considerably to some other value types. But regardless it allows for a lot less string matching and flexibility.

Another set of values which is well specced are transform values: translate, rotate, scale, etc. This is great because if we wanted to change one of these values on an element without Typed OM, it can be tricky, especially if we’ve set more than one.

.myElement {   transform: rotate(10deg) scale(1.2); }

Let’s say we wanted to increase the rotation. If we access this property with getComputedStyle() a matrix is returned.

const transform = getComputedStyle(myElement).transform; // returns matrix(0.984808, 0.173648, -0.173648, 0.984808, 0, 0)

With the transforms we have on the element, we can’t possibly pull out one value from the matrix. I’m not going to go all vectors, scalar values, and dot product here, but suffice to say, you can’t pull out one value once the matrix has been formed. There are definitely going to be numerous mappings.

If you have just a transform or scale, this is possible by string matching where the value is in the matrix. But that’s information for another day.

We could use custom properties to set the value of these transforms and update those:

.myElement {   --rotate: 10deg;   transform: rotate(var(--rotate)) scale(1.2); }
myElement.style.setProperty('--rotate', '15deg');

However, we need to know the name of the custom property and we are still passing in a string.

Enter Typed OM. Let’s take a look at what’s returned from the computedStyleMap:

myElement.computedStyleMap().get('transform'); /* returns CSSTransformValue {   0: CSSRotate {...}   1: CSSScale {...} } */

Each transform value has its own type. There’s CSSRotate and CSSScale for the above code. As well as all the others like skew and translate. So instead of dealing with matrix, or still working with strings, we can create these types and apply a CSSTransformValue with them.

const newTransform = new CSSTransformValue([   new CSSRotate(CSS.deg(15)),   new CSSScale(CSS.number(1.2), CSS.number(1.2)) ]) myElement.attributeStyleMap.set('transform', newTransform);

Notice how we’re creating the transform types with the class method and the new keyword, rather than the factory method used with the numerical values.

We have a lot more control over each individual value, something much needed when we declare multiple values in CSS.

I put together a Pen with all this example code here.

It’s the foundations

As we begin to get more familiar with other API’s within the Houdini suite, the benefits of all of this will become even more obvious. When we declare a new custom property with the Properties and Values API, we set a type and get automatic error handling, for instance. These value types are also passed into the worklets of the Paint API and Layout API, so we can use the power there too.

There are more types I haven’t mentioned, more types to come and really a lot more to write about. If it hasn’t been already, Typed OM is being implemented in all major browsers at this time. It certainly piqued my interest this year, so look out for it as 2020 comes around!

The post The Typed Object Model appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

The (Developer’s) Growth Model

I really like the post “The Designer’s Growth Model” by Dennis Hambeukers. Dennis just invented this model, but it’s based on some existing ideas and it all rings true for me. Let me try to summarize the five stages as he lays them out for designers.

  1. Producers: You learn how to design. You learn fundamentals, you practice, you get good at doing design work and producing beautiful functional things. Then you have this “crisis” moment before the next stage where you find you can’t do enough work on your own and that you need to be able to scale your efforts, with multiple human beings and working on systems — and that’s an entirely new skill.
  2. Architects: Now that you’ve succeeded in scaling through team building and systems thinking, the next crisis moment is that that this the work still might be isolated, and too focused on internal thinking. To grow, you’ll need to work with people outside the design bubble, and understand problems more holistically.
  3. Connectors: Now that you’ve succeeded in being more collaborative across an entire organization and being a real problem solver, the next crisis moment is when everything becomes organizationally complicated. Just delivering products isn’t enough, because you’re involved deeply across the organization and you’re responsible for the success of what is delivered.
  4. Scientists: Now, you measure everything. You know what works and what doesn’t because you test it and can prove it, along with using all the skills you’ve honed along the way. Your next crisis is figuring out how to translate your work into actual change.
  5. Visionaries: You’re a leader now. You have an understanding of how the whole organization ticks, and you are a force for change.
From The Designer’s Growth Model

I think this can applies just as well to web development, with very little change. I can relate in many ways. I started plucking away at building sites alone. I found more success and was able to build bigger things by working with other people. At some point, it was clear to me that things don’t revolve around development. Development is merely one part of a car that doesn’t drive at all without many other parts. Even today, it’s clearer to me that I can be more effective and drive more positive change the more I know about all of the parts.

Not that I’ve completed my journey. If I had to map myself directly onto this model, I’m probably barely on step three — But a model is just a model. It’s not meant to be a perfect roadmap for everybody. Your own career path will be twistier than this. You might even experience bits from all the levels in different doses along the way.

The post The (Developer’s) Growth Model appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

The (Developer’s) Growth Model

I really like the post “The Designer’s Growth Model” by Dennis Hambeukers. Dennis just invented this model, but it’s based on some existing ideas and it all rings true for me. Let me try to summarize the five stages as he lays them out for designers.

  1. Producers: You learn how to design. You learn fundamentals, you practice, you get good at doing design work and producing beautiful functional things. Then you have this “crisis” moment before the next stage where you find you can’t do enough work on your own and that you need to be able to scale your efforts, with multiple human beings and working on systems — and that’s an entirely new skill.
  2. Architects: Now that you’ve succeeded in scaling through team building and systems thinking, the next crisis moment is that that this the work still might be isolated, and too focused on internal thinking. To grow, you’ll need to work with people outside the design bubble, and understand problems more holistically.
  3. Connectors: Now that you’ve succeeded in being more collaborative across an entire organization and being a real problem solver, the next crisis moment is when everything becomes organizationally complicated. Just delivering products isn’t enough, because you’re involved deeply across the organization and you’re responsible for the success of what is delivered.
  4. Scientists: Now, you measure everything. You know what works and what doesn’t because you test it and can prove it, along with using all the skills you’ve honed along the way. Your next crisis is figuring out how to translate your work into actual change.
  5. Visionaries: You’re a leader now. You have an understanding of how the whole organization ticks, and you are a force for change.
From The Designer’s Growth Model

I think this can applies just as well to web development, with very little change. I can relate in many ways. I started plucking away at building sites alone. I found more success and was able to build bigger things by working with other people. At some point, it was clear to me that things don’t revolve around development. Development is merely one part of a car that doesn’t drive at all without many other parts. Even today, it’s clearer to me that I can be more effective and drive more positive change the more I know about all of the parts.

Not that I’ve completed my journey. If I had to map myself directly onto this model, I’m probably barely on step three — But a model is just a model. It’s not meant to be a perfect roadmap for everybody. Your own career path will be twistier than this. You might even experience bits from all the levels in different doses along the way.

The post The (Developer’s) Growth Model appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

An Introduction and Guide to the CSS Object Model (CSSOM)

If you’ve been writing JavaScript for some time now, it’s almost certain you’ve written some scripts dealing with the Document Object Model (DOM). DOM scripting takes advantage of the fact that a web page opens up a set of APIs (or interfaces) so you can manipulate and otherwise deal with elements on a page.

But there’s another object model you might want to become more familiar with: The CSS Object Model (CSSOM). Likely you’ve already used it but didn’t necessarily realize it.

In this guide, I’m going to go through many of the most important features of the CSSOM, starting with stuff that’s more commonly known, then moving on to some more obscure, but practical, features.

What is the CSSOM?

According to MDN:

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.

MDN’s info is based on the official W3C CSSOM specification. That W3C document is a somewhat decent way to get familiar with what’s possible with the CSSOM, but it’s a complete disaster for anyone looking for some practical coding examples that put the CSSOM APIs into action.

MDN is much better, but still largely lacking in certain areas. So for this post, I’ve tried to do my best to create useful code examples and demos of these interfaces in use, so you can see the possibilities and mess around with the live code.

As mentioned, the post starts with stuff that’s already familiar to most front-end developers. These common features are usually lumped in with DOM scripting, but they are technically part of the larger group of interfaces available via the CSSOM (though they do cross over into the DOM as well).

Inline Styles via element.style

The most basic way you can manipulate or access CSS properties and values using JavaScript is via the style object, or property, which is available on all HTML elements. Here’s an example:

document.body.style.background = 'lightblue';

Most of you have probably seen or used that syntax before. I can add to or change the CSS for any object on the page using that same format: element.style.propertyName.

In that example, I’m changing the value of the background property to lightblue. Of course, background is shorthand. What if I want to change the background-color property? For any hyphenated property, just convert the property name to camel case:

document.body.style.backgroundColor = 'lightblue';

In most cases, a single-word property would be accessed in this way by the single equivalent word in lowercase, while hyphenated properties are represented in camel case. The one exception to this is when using the float property. Because float is a reserved word in JavaScript, you need to use cssFloat (or styleFloat if you’re supporting IE8 and earlier). This is similar to the HTML for attribute being referenced as htmlFor when using something like getAttribute().

Here’s a demo that uses the style property to allow the user to change the background color of the current page:

See the Pen Using the style Object to Change the Background Color by Louis Lazaris (@impressivewebs) on CodePen.

So that’s an easy way to define a CSS property and value using JavaScript. But there’s one huge caveat to using the style property in this way: This will only apply to inline styles on the element.

This becomes clear when you use the style property to read CSS:

document.body.style.backgroundColor = 'lightblue'; console.log(document.body.style.backgroundColor); // "lightblue"

In the example above, I’m defining an inline style on the <body> element, then I’m logging that same style to the console. That’s fine. But if I try to read another property on that element, it will return nothing — unless I’ve previously defined an inline style for that element in my CSS or elsewhere in my JavaScript. For example:

console.log(document.body.style.color); // Returns nothing if inline style doesn't exist

This would return nothing even if there was an external stylesheet that defined the color property on the <body> element, as in the following CodePen:

See the Pen element.style Reads Only Inline Styles by Louis Lazaris (@impressivewebs) on CodePen.

Using element.style is the simplest and most common way to add styles to elements via JavaScript. But as you can see, this clearly has some significant limitations, so let’s look at some more useful techniques for reading and manipulating styles with JavaScript.

Getting Computed Styles

You can read the computed CSS value for any CSS property on an element by using the window.getComputedStyle() method:

window.getComputedStyle(document.body).background; // "rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box"

Well, that’s an interesting result. In a way, window.getComputedStyle() is the style property’s overly-benevolent twin. While the style property gives you far too little information about the actual styles on an element, window.getComputedStyle() can sometimes give you too much.

See the Pen The getComputedStyle() Method Can Read any CSS Property by Louis Lazaris (@impressivewebs) on CodePen.

In the example above, the background property of the <body> element was defined using a single value. But the getComputedStyle() method returns all values contained in background shorthand. The ones not explicitly defined in the CSS will return the initial (or default) values for those properties.

This means, for any shorthand property, window.getComputedStyle() will return all the initial values, even if none of them is defined in the CSS:

See the Pen window.getComputedStyle() Returns All Longhand Values for a Shorthand Property by Louis Lazaris (@impressivewebs) on CodePen.

Similarly, for properties like width and height, it will reveal the computed dimensions of the element, regardless of whether those values were specifically defined anywhere in the CSS, as the following interactive demo shows:

See the Pen window.getComputedStyle() Returns Width and Height Values Even if Not Defined in the CSS by Louis Lazaris (@impressivewebs) on CodePen.

Try resizing the parent element in the above demo to see the results. This is somewhat comparable to reading the value of window.innerWidth, except this is the computed CSS for the specified property on the specified element and not just a general window or viewport measurement.

There are a few different ways to access properties using window.getComputedStyle(). I’ve already demonstrated one way, which uses dot-notation to add the camel-cased property name to the end of the method. You can see three different ways to do it in the following code:

// dot notation, same as above window.getComputedStyle(el).backgroundColor;  // square bracket notation window.getComputedStyle(el)['background-color'];  // using getPropertyValue() window.getComputedStyle(el).getPropertyValue('background-color');

The first line uses the same format as in the previous demo. The second line is using square bracket notation, a common JavaScript alternative to dot notation. This format is not recommended and code linters will warn about it. The third example uses the getPropertyValue() method.

The first example requires the use of camel casing (although in this case both float and cssFloat would work) while the next two access the property via the same syntax as that used in CSS (with hyphens, often called “kebab case”).

Here’s the same demo as the previous, but this time using getPropertyValue() to access the widths of the two elements:

See the Pen Using window.getComputedStyle() along with getPropertyValue() by Louis Lazaris (@impressivewebs) on CodePen.

Getting Computed Styles of Pseudo-Elements

One little-known tidbit about window.getComputedStyle() is the fact that it allows you to retrieve style information on pseudo-elements. You’ll often see a window.getComputedStyle() declaration like this:

window.getComputedStyle(document.body, null).width;

Notice the second argument, null, passed into the method. Firefox prior to version 4 required a second argument, which is why you might see it used in legacy code or by those accustomed to including it. But it’s not required in any browser currently in use.

That second optional parameter is what allows me to specify that I’m accessing the computed CSS of a pseudo-element. Consider the following CSS:

.box::before {   content: 'Example';   display: block;   width: 50px; }

Here I’m adding a ::before pseudo-element inside the .box element. With the following JavaScript, I can access the computed styles for that pseudo-element:

let box = document.querySelector('.box'); window.getComputedStyle(box, '::before').width; // "50px"

See the Pen Using getComputedStyle() to get styles from a pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

You can also do this for other pseudo-elements like ::first-line, as in the following code and demo:

let p = document.querySelector('.box p'); window.getComputedStyle(p, '::first-line').color;

See the Pen Using getComputedStyle() to get styles from a pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

And here’s another example using the ::placeholder pseudo-element, which apples to <input> elements:

let input = document.querySelector('input'); window.getComputedStyle(input, '::placeholder').color

See the Pen Using getComputedStyle() to get styles from a ::placeholder pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

The above works in the latest Firefox, but not in Chrome or Edge (I’ve filed a bug report for Chrome).

It should also be noted that browsers have different results when trying to access styles for a non-existent (but valid) pseudo-element compared to a pseudo-element that the browser doesn’t support at all (like a made up ::banana pseudo-element). You can try this out in various browsers using the following demo:

See the Pen Testing getComputedStyle() on non-existent pseudo-elements by Louis Lazaris (@impressivewebs) on CodePen.

As a side point to this section, there is a Firefox-only method called getDefaultComputedStyle() that is not part of the spec and likely never will be.

The CSSStyleDeclaration API

Earlier when I showed you how to access properties via the style object or using getComputedStyle(), in both cases those techniques were exposing the CSSStyleDeclaration interface.

In other words, both of the following lines will return a CSSStyleDeclaration object on the document’s body element:

document.body.style; window.getComputedStyle(document.body);

In the following screenshot you can see what the console produces for each of these lines:

The CSSStyleDeclaration API in the DevTools console

In the case of getComputedStyle(), the values are read-only. In the case of element.style, getting and setting the values is possible but, as mentioned earlier, these will only affect the document’s inline styles.

setProperty(), getPropertyValue(), and item()

Once you’ve exposed a CSSStyleDeclaration object in one of the above ways, you have access to a number of useful methods to read or manipulate the values. Again, the values are read-only in the case of getComputedStyle(), but when used via the style property, some methods are available for both getting and setting.

Consider the following code and demo:

let box = document.querySelector('.box');  box.style.setProperty('color', 'orange'); box.style.setProperty('font-family', 'Georgia, serif'); op.innerHTML = box.style.getPropertyValue('color'); op2.innerHTML = `$ {box.style.item(0)}, $ {box.style.item(1)}`;

See the Pen Using Three Different Methods of the CSSStyleDeclaration API by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m using three different methods of the style object:

  • The setProperty() method. This takes two arguments, each a string: The property (in regular CSS notation) and the value you wish to assign to the property.
  • The getPropertyValue() method. This takes a single argument: The property whose value you want to obtain. This method was used in a previous example using getComputedStyle(), which, as mentioned, likewise exposes a CSSStyleDeclaration object.
  • The item() method. This takes a single argument, which is a positive integer representing the index of the property you want to access. The return value is the property name at that index.

Keep in mind that in my simple example above, there are only two styles added to the element’s inline CSS. This means that if I were to access item(2), the return value would be an empty string. I’d get the same result if I used getPropertyValue() to access a property that isn’t set in that element’s inline styles.

Using removeProperty()

In addition to the three methods mentioned above, there are two others exposed on a CSSStyleDeclaration object. In the following code and demo, I’m using the removeProperty() method:

box.style.setProperty('font-size', '1.5em'); box.style.item(0) // "font-size"  document.body.style.removeProperty('font-size'); document.body.style.item(0); // ""

See the Pen Using the removeProperty() method of the CSSSTyleDeclaration API by Louis Lazaris (@impressivewebs) on CodePen.

In this case, after I set font-size using setProperty(), I log the property name to ensure it’s there. The demo then includes a button that, when clicked, will remove the property using removeProperty().

In the case of setProperty() and removeProperty(), the property name that you pass in is hyphenated (the same format as in your stylesheet), rather than camel-cased. This might seem confusing at first, but the value passed in is a string in this example, so it makes sense.

Getting and Setting a Property’s Priority

Finally, here’s an interesting feature that I discovered while researching this article: The getPropertyPriority() method, demonstrated with the code and CodePen below:

box.style.setProperty('font-family', 'Georgia, serif', 'important'); box.style.setProperty('font-size', '1.5em');  box.style.getPropertyPriority('font-family'); // important op2.innerHTML = box.style.getPropertyPriority('font-size'); // ""

See the Pen Using getPropertyPriority() to get a property’s “importance” by Louis Lazaris (@impressivewebs) on CodePen.

In the first line of that code, you can see I’m using the setProperty() method, as I did before. However, notice I’ve included a third argument. The third argument is an optional string that defines whether you want the property to have the !important keyword attached to it.

After I set the property with !important, I use the getPropertyPriority() method to check that property’s priority. If you want the property to not have importance, you can omit the third argument, use the keyword undefined, or include the third argument as an empty string.

And I should emphasize here that these methods would work in conjunction with any inline styles already placed directly in the HTML on an element’s style attribute.

So if I had the following HTML:

<div class="box" style="border: solid 1px red !important;">

I could use any of the methods discussed in this section to read or otherwise manipulate that style. And it should be noted here that since I used a shorthand property for this inline style and set it to !important, all of the longhand properties that make up that shorthand will return a priority of important when using getPropertyPriority(). See the code and demo below:

// These all return "important" box.style.getPropertyPriority('border')); box.style.getPropertyPriority('border-top-width')); box.style.getPropertyPriority('border-bottom-width')); box.style.getPropertyPriority('border-color')); box.style.getPropertyPriority('border-style'));

See the Pen Using getPropertyPriority() to check the priority of longhand properties by Louis Lazaris (@impressivewebs) on CodePen.

In the demo, even though I explicitly set only the border property in the style attribute, all the associated longhand properties that make up border will also return a value of important.

The CSSStyleSheet Interface

So far, much of what I’ve considered deals with inline styles (which often aren’t that useful) and computed styles (which are useful, but are often too specific).

A much more useful API that allows you to retrieve a stylesheet that has readable and writable values, and not just for inline styles, is the CSSStyleSheet API. The simplest way to access information from a document’s stylesheets is using the styleSheets property of the current document. This exposes the CSSStyleSheet interface.

For example, the line below uses the length property to see how many stylesheets the current document has:

document.styleSheets.length; // 1

I can reference any of the document’s stylesheets using zero-based indexing:

document.styleSheets[0];

If I log that stylesheet to my console, I can view the methods and properties available:

The CSSStyleSheet Interface in the DevTools Console

The one that will prove useful is the cssRules property. This property provides a list of all CSS rules (including declaration blocks, at-rules, media rules, etc.) contained in that stylesheet. In the following sections, I’ll detail how to utilize this API to manipulate and read styles from an external stylesheet.

Working with a Stylesheet Object

For the purpose of simplicity, let’s work with a sample stylesheet that has only a handful of rules in it. This will allow me to demonstrate how to use the CSSOM to access the different parts of a stylesheet in a similar way to accessing elements via DOM scripting.

Here is the stylesheet I’ll be working with:

* {   box-sizing: border-box; }  body {   font-family: Helvetica, Arial, sans-serif;   font-size: 2em;   line-height: 1.4; }  main {   width: 1024px;   margin: 0 auto !important; }  .component {   float: right;   border-left: solid 1px #444;   margin-left: 20px; }  @media (max-width: 800px) {   body {     line-height: 1.2;   }    .component {     float: none;     margin: 0;   } }  a:hover {   color: lightgreen; }  @keyframes exampleAnimation {   from {     color: blue;   }      20% {     color: orange;   }      to {     color: green;   } }  code {   color: firebrick; }

There’s a number of different things I can attempt with this example stylesheet and I’ll demonstrate a few of those here. First, I’m going to loop through all the style rules in the stylesheet and log the selector text for each one:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('p');  for (i of myRules) {   if (i.type === 1) {     p.innerHTML += `<c​ode>$ {i.selectorText}</c​ode><br>`;   } }

See the Pen Working with CSSStyleSheet – Logging the Selector Text by Louis Lazaris (@impressivewebs) on CodePen.

A couple of things to take note of in the above code and demo. First, I cache a reference to the cssRules object for my stylesheet. Then I loop over all the rules in that object, checking to see what type each one is.

In this case, I want rules that are type 1, which represents the STYLE_RULE constant. Other constants include IMPORT_RULE (3), MEDIA_RULE (4), KEYFRAMES_RULE (7), etc. You can view a full table of these constants in this MDN article.

When I confirm that a rule is a style rule, I print the selectorText property for each of those style rules. This will produce the following lines for the specified stylesheet:

* body main .component a:hover code

The selectorText property is a string representation of the selector used on that rule. This is a writable property, so if I want I can change the selector for a specific rule inside my original for loop with the following code:

if (i.selectorText === 'a:hover') {   i.selectorText = 'a:hover, a:active'; }

See the Pen Working with the CSSStyleSheet API – Changing the Selector Text by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m looking for a selector that defines :hover styles on my links and expanding the selector to apply the same styles to elements in the :active state. Alternatively, I could use some kind of string method or even a regular expression to look for all instances of :hover, and then do something from there. But this should be enough to demonstrate how it works.

Accessing @media Rules with the CSSOM

You’ll notice my stylesheet also includes a media query rule and a keyframes at-rule block. Both of those were skipped when I searched for style rules (type 1). Let’s now find all @media rules:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('.output');  for (i of myRules) {   if (i.type === 4) {     for (j of i.cssRules) {       p.innerHTML += `<c​ode>$ {j.selectorText}</c​ode><br>`;     }   } }

Based on the given stylesheet, the above will produce:

body .component

See the Pen Working with the CSSStyleSheet API – Accessing @media Rules by Louis Lazaris (@impressivewebs) on CodePen.

As you can see, after I loop through all the rules to see if any @media rules exist (type 4), I then loop through the cssRules object for each media rule (in this case, there’s only one) and log the selector text for each rule inside that media rule.

So the interface that’s exposed on a @media rule is similar to the interface exposed on a stylesheet. The @media rule, however, also includes a conditionText property, as shown in the following snippet and demo:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('.output');  for (i of myRules) {   if (i.type === 4) {     p.innerHTML += `<c​ode>$ {i.conditionText}</c​ode><br>`;     // (max-width: 800px)    } }

See the Pen Working with the CSSStyleSheet API – Accessing @media Rules by Louis Lazaris (@impressivewebs) on CodePen.

This code loops through all media query rules and logs the text that determines when that rule is applicable (i.e. the condition). There’s also a mediaText property that returns the same value. According to the spec, you can get or set either of these.

Accessing @keyframes Rules with the CSSOM

Now that I’ve demonstrated how to read information from a @media rule, let’s consider how to access a @keyframes rule. Here’s some code to get started:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('.output');  for (i of myRules) {   if (i.type === 7) {     for (j of i.cssRules) {      p.innerHTML += `<c​ode>$ {j.keyText}</c​ode><br>`;     }   } }

See the Pen Working with the CSSStyleSheet API – Accessing @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m looking for rules that have a type of 7 (i.e. @keyframes rules). When one is found, I loop through all of that rule’s cssRules and log the keyText property for each. The log in this case will be:

"0%" "20%" "100%"

You’ll notice my original CSS uses from and to as the first and last keyframes, but the keyText property computes these to 0% and 100%. The value of keyText can also be set. In my example stylesheet, I could hard code it like this:

// Read the current value (0%) document.styleSheets[0].cssRules[6].cssRules[0].keyText;  // Change the value to 10% document.styleSheets[0].cssRules[6].cssRules[0].keyText = '10%'  // Read the new value (10%) document.styleSheets[0].cssRules[6].cssRules[0].keyText;

See the Pen Working with the CSSStyleSheet API – Setting @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

Using this, we can dynamically alter an animation’s keyframes in the flow of a web app or possibly in response to a user action.

Another property available when accessing a @keyframes rule is name:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('.output');  for (i of myRules) {   if (i.type === 7) {     p.innerHTML += `<c​ode>$ {i.name}</c​ode><br>`;   } }

See the Pen Working with the CSSStyleSheet API – Getting the name of a @keyframes rule by Louis Lazaris (@impressivewebs) on CodePen.

Recall that in the CSS, the @keyframes rule looks like this:

@keyframes exampleAnimation {   from {     color: blue;   }      20% {     color: orange;   }      to {     color: green;   } }

Thus, the name property allows me to read the custom name chosen for that @keyframes rule. This is the same name that would be used in the animation-name property when enabling the animation on a specific element.

One final thing I’ll mention here is the ability to grab specific styles that are inside a single keyframe. Here’s some example code with a demo:

let myRules = document.styleSheets[0].cssRules,     p = document.querySelector('.output');  for (i of myRules) {   if (i.type === 7) {     for (j of i.cssRules) {       p.innerHTML += `<c​ode>$ {j.style.color}</c​ode><br>`;     }   } }

See the Pen Working with the CSSStyleSheet API – Accessing Property Values inside @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this example, after I find the @keyframes rule, I loop through each of the rules in the keyframe (e.g. the “from” rule, the “20%” rule, etc). Then, within each of those rules, I access an individual style property. In this case, since I know color is the only property defined for each, I’m merely logging out the color values.

The main takeaway in this instance is the use of the style property, or object. Earlier I showed how this property can be used to access inline styles. But in this case, I’m using it to access the individual properties inside of a single keyframe.

You can probably see how this opens up some possibilities. This allows you to modify an individual keyframe’s properties on the fly, which could happen as a result of some user action or something else taking place in an app or possibly a web-based game.

Adding and Removing CSS Declarations

The CSSStyleSheet interface has access to two methods that allow you to add or remove an entire rule from a stylesheet. The methods are: insertRule() and deleteRule(). Let’s see both of them in action manipulating our example stylesheet:

let myStylesheet = document.styleSheets[0]; console.log(myStylesheet.cssRules.length); // 8  document.styleSheets[0].insertRule('article { line-height: 1.5; font-size: 1.5em; }', myStylesheet.cssRules.length); console.log(document.styleSheets[0].cssRules.length); // 9

See the Pen Working with the CSSStyleSheet API – Inserting Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this case, I’m logging the length of the cssRules property (showing that the stylesheet originally has 8 rules in it), then I add the following CSS as an individual rule using the insertRule() method:

article {   line-height: 1.5;   font-size: 1.5em; }

I log the length of the cssRules property again to confirm that the rule was added.

The insertRule() method takes a string as the first parameter (which is mandatory), comprising the full style rule that you want to insert (including selector, curly braces, etc). If you’re inserting an at-rule, then the full at-rule, including the individual rules nested inside the at-rule can be included in this string.

The second argument is optional. This is an integer that represents the position, or index, where you want the rule inserted. If this isn’t included, it defaults to 0 (meaning the rule will be inserted at the beginning of the rules collection). If the index happens to be larger than the length of the rules object, it will throw an error.

The deleteRule() method is much simpler to use:

let myStylesheet = document.styleSheets[0]; console.log(myStylesheet.cssRules.length); // 8  myStylesheet.deleteRule(3); console.log(myStylesheet.cssRules.length); // 7

See the Pen Working with the CSSStyleSheet API – Deleting Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this case, the method accepts a single argument that represents the index of the rule I want to remove.

With either method, because of zero-based indexing, the selected index passed in as an argument has to be less than the length of the cssRules object, otherwise it will throw an error.

Revisiting the CSSStyleDeclaration API

Earlier I explained how to access individual properties and values declared as inline styles. This was done via element.style, exposing the CSSStyleDeclaration interface.

The CSSStyleDeclaration API, however, can also be exposed on an individual style rule as a subset of the CSSStyleSheet API. I already alluded to this when I showed you how to access properties inside a @keyframes rule. To understand how this works, compare the following two code snippets:

<div style="color: lightblue; width: 100px; font-size: 1.3em !important;"></div>
.box {   color: lightblue;   width: 100px;   font-size: 1.3em !important; }

The first example is a set of inline styles that can be accessed as follows:

document.querySelector('div').style

This exposes the CSSStyleDeclaration API, which is what allows me to do stuff like element.style.color, element.style.width, etc.

But I can expose the exact same API on an individual style rule in an external stylesheet. This means I’m combining my use of the style property with the CSSStyleSheet interface.

So the CSS in the second example above, which uses the exact same styles as the inline version, can be accessed like this:

document.styleSheets[0].cssRules[0].style

This opens up a single CSSStyleDeclaration object on the one style rule in the stylesheet. If there were multiple style rules, each could be accessed using cssRules[1], cssRules[2], cssRules[3], and so on.

So within an external stylesheet, inside of a single style rule that is of type 1, I have access to all the methods and properties mentioned earlier. This includes setProperty(), getPropertyValue(), item(), removeProperty(), and getPropertyPriority(). In addition to this, those same features are available on an individual style rule inside of a @keyframes or @media rule.

Here’s a code snippet and demo that demonstrates how these methods would be used on an individual style rule in our sample stylesheet:

// Grab the style rules for the body and main elements let myBodyRule = document.styleSheets[0].cssRules[1].style,     myMainRule = document.styleSheets[0].cssRules[2].style;  // Set the bg color on the body myBodyRule.setProperty('background-color', 'peachpuff');  // Get the font size of the body myBodyRule.getPropertyValue('font-size');  // Get the 5th item in the body's style rule myBodyRule.item(5);  // Log the current length of the body style rule (8) myBodyRule.length;  // Remove the line height myBodyRule.removeProperty('line-height');  // log the length again (7) myBodyRule.length;  // Check priority of font-family (empty string) myBodyRule.getPropertyPriority('font-family');  // Check priority of margin in the "main" style rule (!important) myMainRule.getPropertyPriority('margin');

See the Pen Working with the style object of an individual style rule in an external Stylesheet by Louis Lazaris (@impressivewebs) on CodePen.

The CSS Typed Object Model… The Future?

After everything I’ve considered in this article, it would seem odd that I’d have to break the news that it’s possible that one day the CSSOM as we know it will be mostly obsolete.

That’s because of something called the CSS Typed OM which is part of the Houdini Project. Although some people have noted that the new Typed OM is more verbose compared to the current CSSOM, the benefits, as outlined in this article by Eric Bidelman, include:

  • Fewer bugs
  • Arithmetic operations and unit conversion
  • Better performance
  • Error handling
  • CSS property names are always strings

For full details on those features and a glimpse into the syntax, be sure to check out the full article.

As of this writing, CSS Typed OM is supported only in Chrome. You can see the progress of browser support in this document.

Final Words

Manipulating stylesheets via JavaScript certainly isn’t something you’re going to do in every project. And some of the complex interactions made possible with the methods and properties I’ve introduced here have some very specific use cases.

If you’ve built some kind of tool that uses any of these APIs I’d love to hear about it. My research has only scratched the surface of what’s possible, but I’d love to see how any of this can be used in real-world examples.

I’ve put all the demos from this article into a CodePen collection, so you can feel free to mess around with those as you like.

The post An Introduction and Guide to the CSS Object Model (CSSOM) appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]