CSS and Javascript working together

Do we need CSS after all?

CSS is not immune to the framework wars. This is a quick look at some of the available CSS frameworks.

Bootstrap

Foundation

Semantic-UI

Susy

Material UI

MaterializeCSS

Gumby

Pure

Metro UI CSS 2.0

Leaf Beta

They all solve the same problem of laying out and styling content but they all have different styles to solve the same problem of providing consistent, reusable and scalable CSS libraries.

Different CSS frameworks present different approaches to building a good CSS suite of tools. The problem is that some of these frameworks (Bootstrap and Foundation in particular) have grown insanely large over the years and they haven’t always provided a customizer to build slimmed down builds until recently (Later builds of Bootstrap 3, Bootstrap 4 and Foundation 5 are the only ones that offer this functionality).

Of course there are people who say that we should just dump CSS altogether and Javascript all the things on the web. You can access the CSS Object Model (CSSOM) via Javascript and the new CSS Typed OM Level 1 from the Houdini project promises to make this even easier.

If we take writing CSS in Javascript to the extreme are to dump CSS frameworks altogether and create all the CSS using Javascript, just like we could with Javascript Styelsheets back in the Netscape 4 days… well, maybe not quite the same way… after all Netscape 4 (4.0 to 4.8) was the only browser that supported JSS.

But I disgress…

The idea is that, since all styles are accessible through Javascript using the style method of the HTMLElement object , we should be able to manipulate the inline styles of elements in the document programmatically. We don’t have to use yet another programming language to create our content. Furthermore, because we are using a full fledged programming language we can create very powerful “style sheets” and not having to worry about silly things like the cascade and specificity.

The associated scripts grabs the elements and assigns them to variables. Then we add click event listeners so when the use clicks on either button the color of the text in the paragraph (id = content) will change to the corresponding color. I’ve also added a third button to reset the color to black using the same method as the other two buttons.

Remember where I said that it the style method would only work with inline properties? This means that if you have a stylesheet associated with the document the style method will not work on these properties on the styleSheet.

We can get around it by using the, extremely cumbersome method show below. It’s broken into three parts. The first part is the HTML we’ll use to demo the system

<div class="boxes box1">
<p>content goes here</p>
</div>

The second part is the CSS we’ll modify in Javascript. It’s two basic rules one for all elements with class boxes and one for the specific element with class box1.

.boxes {
padding: 2em;
}
.box1 {
background-color: green;
}

The final part is the Javascript that will modify the CSS.

We first extract the stylesheet we want to work on into a variable to save ourselves some typing.

We then navigate the rules of the stylesheet using a 0-based scale and change the style attribute for that rule using Javascript’s camel-case syntax. In this example we change the first rule’s second style (0-based) background color.

Getting styles for an element

Once again, let’s start with thesimple solution.

But according to MDN:

The style property is not useful for learning about the element’s style in general, since it represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. To get the values of all CSS properties for an element you should use window.getComputedStyle() instead.

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets after all processing is done. The returned style is live and will update itself whenever the styles for the element change.

In large projects it may become counter productive to manually search for each property in every stylesheet. If you need to work with larger stylesheets you can use something like the function below to analyze the element you want to work with.

The function will log all the properties inlined into the element’s style. It will then iterate over the element’s computer style and display those values as well.

We are doing math, converting a number to a string to append a unit just to have the browser parse that string and convert it back to a number for the CSS engine. This gets uglier when the more complex your styles become. This also means we should always know what the final unit type for our calculation is and that we can’t skip any unit assignment or the script will fail in unpredictable ways.

Typed CSS will reduce some of these issues.

Instead of strings you will be working on an element’s StylePropertyMap or styleMap, where each CSS attribute has it’s own key and corresponding value type.

Attributes like width have LengthValue as their value type. A LengthValue is a dictionary of all CSS units like em, rem, px, percent, etc.

Some properties like box-sizing just accept certain keywords and therefore have a KeywordValue value type. The validity of those attributes could then be checked at runtime.

Mix and matching Javascript and CSS example: Font Face Observer

The best way I’ve seen of combining CSS and Javascript is the Font Face Observer library by Bram Stein. It leverages CSS and Javascript to make sure fonts are loaded successfully before they are used and that a suitable fallback is available if fonts fail to load. Instead of manipulating individual CSS selectors with Javascript we add and remove pre-defined classes.

The css is basic. We create three definitions of our body class:

The first one loads when the classes for the following use cases are not loaded

Since we configured different font stacks for each of the classes we get the a basic system font loaded quickly while the web font loads. Once it has loaded the web font replaces the original. Make sure you use similar fonts throughout the project. A really good tool to make sure your fonts match and what changes, if any, you need to make to your replacement fonts is Monica Dinculescu’s Font style matcher

Also take into account that, in an ideal world, we would load 4 different fonts for each typeface we use: One for the following types:

Normal font

Bold

Italics

Bold / Italics

If the browser doesn’t find a suitable bold or italic version of the typeface you are using it will create algorithmic replacements. As Alan Stearns puts it:

Browsers can do terrible things to type. If text is styled as bold or italic and the typeface family does not include a bold or italic font, browsers will compensate by trying to create bold and italic styles themselves. The results are an awkward mimicry of real type design.