Why Everyone Is Fighting About CSS/UX and JS

Why Everyone Is Fighting About CSS/UX and JS

Why Everyone Is Fighting About CSS/UX and JS

TL;DR: There isn’t one. There’s no short way to say any of this, yet one of the reasons you keep fighting is because you misunderstand what the fight is about. Read the damn article. Please and thank you.

I hate intros. Let’s just dive in and I’ll fill you in where pertinent.

The Great Divide

Chris Coiyer’s essay “The Great Divide” broke the frontend dev community, inviting no small amount of snarkiness and drama on Twitter and elsewhere. In case you haven’t read the piece (and you should), it revolves around an observed division between frontend developers who use primarily JavaScript-related technologies to do their job, and frontend developers for whom JavaScript is only one of the many technologies they employ to do their more UX-centric job. The thing that everyone seems to be missing is that this is not a prescriptive view of how frontend-land should work, but rather, a descriptive view derived from real-life interviews Chris and his buddy Dave Rupert have conducted on their podcast ShopTalk Show (dot com).

In other words, the split is real. Chris and Dave are merely putting it into words.

Chris concludes in “The Great Divide” that this rift in focus is happening because frontend-land has basically ballooned away from the old context where frontend development was comprised of merely styling server-rendered components. He notes that many frontend developers are using JavaScript in a way more closely reminiscent of usual MVC-style backend programming, while others are focusing on using a more rounded set of tools, and primarily CSS, to make the frontend experience better and more accessible, and thus, if we’re to helpfully describe the jobs frontend developers are being hired to do, we should be distinguishing between JS Engineers and UX Engineers.

Class Warfare

The discussion, though, immediately devolved into whether JS Engineers (I’ve gone ahead and accepted Chris’s proposed nomenclature) do more work than UX Engineers, and whether UX Engineers deserve to be paid the same as JS Engineers.

I should note: if you’ve seen the discussion online and the outline I’m presenting doesn’t jibe with your version of the events, that’s fine. The web is a big place, and it’s entirely possible you and I have witnessed two sides of the same coin. I’m trying to contextualize what I’ve seen with this narrative I’m building; I hope that’s OK with you.

Anyway, as a surprise to nobody in the industry, we have a recurring theme of derision and general snootiness toward other people’s tech, an attitude which developer Aurynn Shaw incisively terms “contempt culture”. In this case, we began to see this contempt target UX Engineers… and I’m certain a number of you reading this are now thinking “you mean designers, though, right? How is design also engineering?”

Because here’s the thing: even when no offense is meant, a lot of people don’t think UX Engineers are a thing, or that they’re glorified web designers at best. I observed this same attitude in the discussions surrounding the ShopTalk interviews of people who were primarily doing design-centric work. I’m not going to nag you one way or the other about whether this is correct; I’m merely pointing out that this is an attitude that people hold.

I’m likewise going to point out that people who take part in this culture of contempt often don’t mean harm with their dismissiveness (citation needed, sure, but it’s my writeup). People are not necessarily trying to be jerks when they dismiss Ruby for being slow, nor when they dismiss JavaScript for “having been written in ten days”, nor when they dismiss Java as tech for stuffy old farts, nor when they dismiss Elixir as a toy language, nor when they dismiss PHP for being PHP, nor when they dismiss web development as “not real programming”, nor when they dismiss UX Engineers as “not engineers”. Sometimes the snootiness is just abrasive opinion based on passive biased observation.

Not many are keen on defending this behavior, though, because to people specializing in the technologies being disdained, these opinions often constitute a direct attack. You can pin a huge asterisk on this point, but basically: turns out when a person feels other people are shitting on the thing that pays the bills, that person might (rightly or understandably, your choice) get defensive. And that’s precisely what we saw on Twitter.

Jen Simmons (W3C’s Working Group, Mozilla, Layout Land) describes the animosity toward UX Engineers as “class warfare”, and shot a number of choice spicy tweets toward a particular lean of JS Engineers:

I’m not doing you the (dis)favor of including any of the shittier tweets thereafter flung in Jen’s direction: it’s the web—use your imagination. On the more sensible side of things, though, this argument gets more nuanced. Dan Abramov (React, Redux, create-react-app) writes:

I’m obviously putting Dan in the JS Engineer camp because, you know, React. Then there are people who don’t fully identify with either of our new frontend designations. For example, Kyle Simpson (You Don’t Know JS, Frontend Masters) writes:

Among other opinions, though, you can see folks beginning to tire of the incessant barrage of negativity. Das Surma (Google, HTTP203) sums it up thusly (and I really wish I could say “Surma surmises” but it’s wrong diction):

Basic as HTML

By the time Surma makes this statement, though, we’ve lost all semblance of a common thread of discussion. It’s no longer about how frondend development is evolving, but about whether CSS and HTML are difficult as technologies, by way of defending people whose job might often go no further programming-wise (though in my case obviously not dismissing the wealth of education and experience required for UX Engineering).

This is where DHH, whose JavaScript framework Stimulus (and indeed his entire work on Rails) pivots on the idea that the web is becoming unnecessarily complex and we’re all better off focusing on making app development as straightforward as possible, gives us his unsurprisingly direct opinion that designing for the web ought to mean making HTML and CSS.

I’ll admit that I think the discussion did seem to have jumped the shark a bit around the time DHH said this (though in the name of defending UX Engineers, so I’m not faulting anyone)… I mean, isn’t the whole point of web technologies to be accessible? Shouldn’t we take pride on the fact that HTML and CSS are as easy as they are powerful?

Wait, what were we talking about?

Somewhere around this point, there seemed to be a shift in the atmosphere: a secondary argument began to emerge… and it is where I think everything became real convoluted, and it’s where people are having trouble reconciling what the hell is even going on with this whole UX vs. JS thing. Because while one side was fighting about whether UX is as cool as JS or whatever, an adjacent and more interesting talk began to make its way forward…

From my personal vantage, it started with DHH, who goes on to make a second appearance in this story with an observation about the state of web technologies, this time in a post about how View Source is on the decline and how we shouldn’t let it die.

(Here Tom Dale throws a spicy one at DHH; I’m including these for no better reason than it’s funny:)

Anyway, the idea that View Source is worth saving is pretty interesting, because I knew I couldn’t be the only one who thinks the original discussion is coalescing into a second and more nuanced conversation, namely: what is going on with the semantic web?

Wait, what? Who is even bringing up the semantic web?

Well, look, allow me a brief leap in context. In case you’re not familiar and didn’t bother reading the article I linked to just now, the semantic web was Sir Tim-Berners Lee’s idea for the future of the web, where web pages would be intelligible to humans as well as computers. To be realistic about it, though, the semantic web ultimately amounted to not much more than a bunch of schema tags that we were supposed to throw into our HTML to make it easier for Google to do their job, but while it’s fun to be cynical about it, let’s not forget the real reason the notion of the semantic web exists: the dream of a decentralized web where everyone owns their data and information silos aren’t a thing. More pertinently, though, the semantic web illustrates that, ever since the beginning of the web, there’s been the idea that the web is meant to be accessible and open.

Agree or disagree—not the point. I’m only claiming this is what is at the heart of this second round of the fight pitting JS against UX: whether or not JS is becoming bloat that is keeping the web from being accessible and open.

As you can probably tell, this also runs in contempt culture territory, because it implies that frontend Javascript technologies are bad for the web. And while I think this argument has more intellectual merit than whether UX engineers are less cool than JS engineers or whatever, as you might infer, things once again got pretty heated. For the sake of brevity, here’s a cursory list of the types of arguments being made:

  • Some people argue that using so much JS on the frontend is creating a scene where the fabric of the web that’s supposed to tie us together is no longer human-accessible (implication being that’s a problem).
  • Some people argue that it doesn’t matter because the web is only a delivery method for digital products.
  • Some people argue that JS frameworks make the web impractical or inaccessible for people with accessibility needs.
  • Some people argue that, while accessibility concerns are a valid criticism, it doesn’t mean that frameworks and best practices aren’t still evolving and this is a solvable problem.
  • Some people argue that frameworks are making people overly reliant on technologies not inherent to the web, and new developers are losing grasp of the possibilities of raw technologies.
  • Some people argue that frameworks help tame the complexity of the web and allow people to become productive faster.
  • Some people argue that frameworks are needlessly bulky and make the web experience worse for people with crappier internet.
  • Some people argue that’s also a solvable problem…

I wanted to back each of those sentiments with individual tweets expressing them concretely, but that’s a lot of work, so I’m using my editorial discretion and not doing any of that. However, you can go on Twitter or Dev.to or Medium and do your own research—people are expressing these opinions.

None of this is new

This whole fight about the state and future of the web has long been a simmering disturbance in the Force, usually felt by developers as no more than a dull background throb, but every once in a while coming back with a jolt. This is evidently one such time. As developers though, we recognize this recurring argument as the worn motif of old, morphed but yet familiar, and existing as long as our industry has existed: what role should computers play on the theme of our collective human experience?

…yeah, OK—I’ll tone down the philosophical flight of fancy.

But you know what I’m saying, at least. This is the industry that coined the hacker ethic, and free software, and open source, and Creative Commons, and “information wants to be free,” and the aforementioned semantic web, and shit, we could even take it as far back as Doug Engelbart’s notion of augmenting human intelligence with computers. All I’m saying is that developers have been known to entertain thoughts about the nature of the relationship between humans and computers.

So one good thing that’s emerged from this fight is a renewed vigor in visiting this topic from the point of view of the web: what do we want out of it? What do we want the web to look like? What’s worth preserving, and what’s expendable? What new features do we want to see? Who’s role is it to bring this all about? And what role will frontend engineers of every persuasion play?

Indeed, some of the people I’ve already mentioned in tweets have some pretty sharp observations on the future of the web. For example, in his excellent talk about the future of JavaScript, Kyle Simpson talks about whether we should let JavaScript become a mere compilation target (relevant bits at 27:50):

And in one of her great videos about modern CSS, Jen Simmons recommends to stop reaching for frameworks such as Bootstrap and to begin to use raw CSS and all its awesome features (relevant bits at 8:29):

And it couldn’t hurt to also watch this other excellent talk about why the semantic web as originally envisioned failed, and what we can do about it (summary slide thrown at around 1:09:24).

But maybe I digress…

Get to the point, author guy

Yeah, ok. My point is that there are a number of us (whoops, I guess I am choosing sides after all) who think the web should be a batteries-included, accessible platform for everyone, and that we should try hard to maintain its open and semantic nature. Some of us (me) even go so far as to buy into Sir Tim Berners-Lee’s idea that the web should be wholly decetralized and become solid scheming turtles all the way down or whatever. In this newly morphed discussion, let’s call this extreme side A.

Then there’s others who think that it doesn’t matter if the web is just a compilation target: that the web only matters insofar as people are using it for real business purposes, and if this is so, then our only concern should be to deliver a good experience to our product’s users, and this hippy-dippy notion of the web as a place where we can hold hands and view readable source be damned. Let’s call this extreme side B.

No doubt, most people will have opinions that fall somewhere along that continuum, rather than at either extreme. To conclude, though:

  1. Chris Coiyer’s “the Great Divide” is meant to be descriptive, not prescriptive, of the state of frontend development.
  2. The conversation of whether UX Engineers should be paid as much as JS Engineers is mired in misunderstanding of what the hell UX Engineers even do and whether the appellation is just a fancy new name for “designers”, a word which in this context seems to carry the weight of substantial misplaced disgust. I would stay away from this.
  3. The conversation among sensible developers centers more around whether it’s OK or not that we’re using so much JS framework magic on the frontend that it’s in fact evolving the industry—less like gradually leveling up a Pokémon, and more akin to forcing a Thunderstone-induced transformation on Pikachu. I think there are good points to be had either way, but everyone involved would probably benefit from being careful not to tread in contempt-culture territory. Not that you need me refereeing your shit, but you know, it’s my blog.
  4. Also, no surprises, but Twitter commenters who are not sensible can indeed be so much fodder for a hefty trash compactor.
  5. But fuck’em, because there’s a neat adult conversation to be had about the future of the web in spite of these people, so let’s, you know, get crackin’ on that front: let’s discuss the role of JS frameworks; let’s discuss whether Web Assembly is really going to replace JavaScript, and whether we want it to; let’s even discuss all the great new features available on the web… There’s a lot to talk about, valid interpretations of our future as web denizens and as developers, and we should definitely sit down and talk it out.

You go first, though.

Teaching CSS to JavaScripters

Some JavaScript professionals do not know CSS as well as they’d like to. In order to help them, PPK decided to write a book “CDD for JavaScripters”, where he will explain CSS in terms that JavaScripters will understand.

But what are those terms? What kind of teaching would JavaScripters expect? Is there a CSS mental model that is different from a JavaScript mental model? Is CSS a programming language? Does that matter for teaching or learning CSS?

PPK will give a brief outline of where he’s standing right now on these questions. The majority of the session will be used for a discussion with the audience. How should he teach CSS? Why is it so hard for some to understand it? What are the least-understood parts of CSS? We hope this discussion will yield valuable feedback.


Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

12 tips for writing clean and scalable JavaScript

10 JavaScript Charting Libraries for Every Data Visualization Need

Tutorial CSS object model through its JavaScript API 🚀🚀🚀

Tutorial CSS object model through its JavaScript API 🚀🚀🚀

Tutorial CSS object model through its JavaScript API - 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...🌟🌟🌟🌟🌟

Tutorial CSS object model through its JavaScript API - 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...

Beyond all preprocessors, transpiler, or whatever web development tool you can think of, one fact still remains true - it's HTML, CSS, and JavaScript that power today's web. Any kind of tool, language and etc., all that remains dependent on these 3 technologies (if we don't count the uprising WebAssembly). They work and interact together, to provide you with limitless possibilities to create newer, better and even more stunning things!

JavaScript is - if we can call it that way - the king of interactivity. Its capabilities as a scripting language itself, combined with numerous web APIs extending its feature-set even further, are truly impressive. Examples of such APIs include the most well-known WebGL API, Canvas API, DOM API, but also a lesser-known set of CSS-related methods, which can be called (unofficially) CSS API. And that's what we're going to explore in today's post!

While the idea of interacting with DOM through its JS API was made really popular thanks to concepts such as JSX and countless JS frameworks, the use of similar techniques with CSS doesn't seem to have that much attention. Of course, CSS-in-JS solutions exist, but the most popular ones are rather based on transpilation, outputting CSS without any additional runtime in production. That's good for performance for sure, as CSS API usage may cause additional reflows, which makes it just as demanding as the use of DOM API. But still, this isn't what we're looking for. What if I tell you that you can not only manipulate DOM elements' styles and CSS classes but also create full-blown stylesheets, just like with HTML, just with the use of JS?

Basics Inline styles

Before we'll dive deep into the complex stuff, let's first remind ourselves some basics. Like the fact that you can edit the given HTMLElement's inline styles by modifying its .style property.

const el = document.createElement("div");

el.style.backgroundColor = "red";
// or
el.style.cssText = "background-color: red";
// or
el.setAttribute("style", "background-color: red");

Setting your style properties directly on the .style object will require you to use camelCase as your property keys, instead of kebab-case. If you have much more inline style properties to set (although, in such case, you may consider using CSS classes), you can do this in a bit more performant way, by setting the .style.cssText property or by setting the style attribute. Keep in mind that this will completely reset the inline styles of your element, and thus, requires you to include all properties (even the unchanged ones) in the string argument. If such micro-optimizations don't interest you (they really shouldn't), and your targeting modern browsers, you can consider using .style with Object.assign(), to set multiple style properties at once.

// ...
Object.assign(el.style, {
    backgroundColor: "red",
    margin: "25px"
});

There's a bit more to these "basics" than you'd probably think of. The .styleobject implements the CSSStyleDeclaration interface. This means that it comes with some interesting properties and methods! This includes known to us .cssText, but also .length (number of set properties), and methods like .item(), .getPropertyValue() and .setPropertyValue(), allowing you to operate on inline styles, without the use of camelCase, and thus - any case conversion. You can find the complete API documented on MDN.

// ...
const propertiesCount = el.style.length;
for(let i = 0; i < propertiesCount; i++) {
    const name = el.style.item(i); // e.g. "background-color"
    const value = el.style.getPropertyValue(name); // e.g. "red"
    const priority = el.style.getPropertyPriority(name); // e.g. "important"

    if(priority === "important") {
        el.style.removeProperty();
    }
}

Just a small tidbit - the .item() method that's most useful during iterations, has the alternate syntax in the form of access by index.

// ...
el.style.item(0) === el.style[0]; // true

CSS classes

Now, let's leave inline styles for a moment and take a look at higher structures - CSS classes. The basics include the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/className" target="_blank">.className</a> which has a form of a string when retrieved and set.

// ...
el.className = "class-one class-two";
el.setAttribute("class", "class-one class-two");

Another way of setting classes string is by setting the class attribute (same for retrieval). But, just like with .style.cssText property, setting.className would require you to include all classes of the given element in the string, including the changed and unchanged ones. Of course, some simple string operations can do the job, but surely there has to be another way... And there is! It's provided to us in the form of slightly-newer.classList property. By "slightly newer" I mean that it isn't supported by IE 9, and only partially supported by IE 10 and IE 11.

The .classList property implements <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList" target="_blank">DOMTokenList</a>, giving you access to a whole bunch of useful methods. Likes of .add(), .remove(), .toggle() and.replace() allow you to change the current set of CSS classes, while others, e.g. .item(), .entries() or .forEach() simplify the iteration process of this index collection.

// ...
const classNames = ["class-one", "class-two", "class-three"];
classNames.forEach(className => {
    if(!el.classList.contains(className)) {
        el.classList.add(className);
    }
});

Stylesheets

Now that we're done with the revision, let's start creating our JS-only stylesheet! First, let's break down all the details behind what's going on.

Going from top to the bottom, we have the <a href="https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList" target="_blank">StyleSheetList</a> interface, implemented by document.styleSheets property. It helps to represent the situation seen in standard HTML code - the use of multiple stylesheets in one document. Whether it's from an external file, URL or within <style/>tag, document.styleSheets collects them all in an indexed collection, implementing standard iteration protocols. With that said, you can access all the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet" target="_blank">CSSStyleSheet</a>s with a simple loop.

for(styleSheet of document.styleSheets){
    console.log(styleSheet);
}

As that's all there is to StyleSheetList, let's go over to CSSStyleSheet itself. It's here where things start to get interesting! CSSStyleSheet extends<a href="https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet" target="_blank">StyleSheet</a> interface, and, with this relation come only a few read-onlyproperties, like .ownerNode, .href, .title or .type, that are mostly taken straight from the place where given stylesheet was declared. Just recall the standard HTML code for loading external CSS file, and you'll know what I'm talking about.

<head>
<link rel="stylesheet" type="text/css" href="style.css" title="Styles">
</head>

So, all the stuff that interests us the most is inside the CSSStyleSheetinterface. Now, we know that HTML document can contain multiple stylesheets, and now... all these stylesheets can contain different rules or even more stylesheets (when using @import) within them! And that's the point we're at. CSSStyleSheet gives you access to two methods -.insertRule() and .deleteRule().

// ...
const ruleIndex = styleSheet.insertRule("div {background-color: red}");
styleSheet.deleteRule(ruleIndex);

These methods operate with indices and CSS-like strings. As CSS rules order is important to decide which one should be used in case of conflict,.insertRule() allows you to pass an optional index for your new rule. Know that some misuses may result in an error, so... just keep it simple.

CSSStyleSheet also has two properties of its own - .ownerRule and.cssRules. While .ownerRule is related to @import stuff, it's the second one - the .cssRules - that interests us the most. Simply put, it's a <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSRuleList" target="_blank">CSSRuleList</a> of<a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSRule" target="_blank">CSSRule</a>s, that can be modified with earlier-mentioned .insertRule()and.deleteRule() methods. Keep in mind, that some browsers may block you from accessing .cssRules property of external CSSStyleSheet from a different origin (domain).

So, what about CSSRuleList? Again, it's an iterable collection of CSSRules, meaning that you can iterate over it, access its CSSRules by their indices or.item() method. What you cannot do though is modifying CSSRuleListdirectly. It can only be done with previously mentioned methods and nothing else.

The CSSRuleList contains object implementing CSSRule interface. This one comes with properties such as .parentStyleSheet and - most importantly -.cssText, containing all the CSS code of the given rule. There's yet one more interesting property - .type. It indicates the type of given CSSRule, according to specified constants. You should remember, that besides the most often use "standard" style-related rules, CSS can consist of e.g. @importor @keyframes (most notably) rules. CSSRules of different types have corresponding interfaces. As you won't be creating them directly, but rather with CSS-like strings, you don't really have to know anything more, that the properties that these extended interfaces provide.

In case of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule" target="_blank">CSSStyleRule</a>, these properties are .selectorText and .style. First one indicates the selector used for the rule in the form of a string, and the second one is an object implementing CSSStyleDeclaration interface, which we've discussed before.

// ...
const ruleIndex = styleSheet.insertRule("div {background-color: red}");
const rule = styleSheet.cssRules.item(ruleIndex);

rule.selectorText; // "div"
rule.style.backgroundColor; // "red"

Implementation

At this point, I think we know enough about CSS-related JavaScript APIs, to create our own, tiny, runtime-based CSS-in-JS implementation. The idea is that we'll create a function, that passed a simple style configuration object, will output a hashed name of newly created CSS class for later use.

So, our workflow here is pretty simple. We need a function that has access to some sort of stylesheet and just use .insertRule() method together with phrased style config to make everything ticking. Let's start with the stylesheet part.

function createClassName(style) {
  // ...
  let styleSheet;
  for (let i = 0; i < document.styleSheets.length; i++) {
    if (document.styleSheets[i].CSSInJS) {
      styleSheet = document.styleSheets[i];
      break;
    }
  }
  if (!styleSheet) {
    const style = document.createElement("style");
    document.head.appendChild(style);
    styleSheet = style.sheet;
    styleSheet.CSSInJS = true;
  }
  // ...
}

If you're using ESM or any other kind of JS module system, you can safely create your stylesheet instance outside the function and not worry about other people accessing it. But, as I wanted to keep this example minimal, we'll just set the .CSSInJS property on our stylesheet as a form of a flag, informing us if this is the one we want to use.

That's pretty much all about the first part of the code snippet above. Now, what if we have to create a new stylesheet for our purposes? There's no straight-forward way of doing this. Our best bet would be to create a new<style/> tag and append it to our HTML document's <head/>section. This automatically adds a new stylesheet to the document.styleSheets list and allows us to access it by the .sheet property of our <style/> tag. Pretty clever, huh?

function createRandomName() {
  const code = Math.random().toString(36).substring(7);
  return `css-${code}`;
}

function phraseStyle(style) {
  const keys = Object.keys(style);
  const keyValue = keys.map(key => {
    const kebabCaseKey = 
        key.replace(/([a-z])([A-Z])/g, "function createRandomName() {
  const code = Math.random().toString(36).substring(7);
  return `css-${code}`;
}

function phraseStyle(style) {
  const keys = Object.keys(style);
  const keyValue = keys.map(key => {
    const kebabCaseKey = 
        key.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
    const value = 
        `${style[key]}${typeof style[key] === "number" ? "px" : ""}`;

    return `${kebabCaseKey}:${value};`;
  });

  return `{${keyValue.join("")}}`;
}
-$2").toLowerCase();
    const value = 
        `${style[key]}${typeof style[key] === "number" ? "px" : ""}`;

    return `${kebabCaseKey}:${value};`;
  });

  return `{${keyValue.join("")}}`;
}

Actually, beyond the tiny tidbit above, there's really no more similarly-interesting stuff going on. Naturally, we first need a way to generate a new,random name for our CSS class. Then, we need to properly phrase our style object, to the form of viable CSS string (or at least part of it). This includes the conversion between camelCase and kebab-case, and, optionally, handling of pixel unit(px) conversion. Oh, and don't forget the semicolon (;) at the end of every key-value pair!

function createClassName(style) {
  const className = createRandomName();
  let styleSheet;
  // ...
  styleSheet.insertRule(`.${className}${phraseStyle(style)}`);
  return className;
}

Then, we go to our main function and make the required adjustments. We generate the random name and insert the CSS rule to the stylesheet. As all out rules are about classes, they all require a dot on their respective beginning for a proper selector. Believe me, it's super easy to forget!

const redRect = createClassName({
  width: 100,
  height: 100,
  backgroundColor: "red"
});

el.classList.add(redRect);

With all set and done, we can finally put our code to the final test! Everything should work just fine! Below is a CodePen to prove that.

What do you think?

As you can see, manipulating CSS from JavaScript level is very interesting. Whether you know it's possible or not, you must admit - it's pretty awesome. Our little example above is only a proof-of-concept. There's a lot more potential within CSS API (or rather APIs). And it's just waiting to be unveiled!

Flexible Text Block with CSS and JavaScript

Flexible Text Block with CSS and JavaScript

How we can create a flexible full-width text using HTML, CSS, & JavaSript? Solution: Responsive Full-Width Text With CSS and JavaScript

I am sure that you get what I am talking about. Basically, This is an experiment to create flexible or responsive text with 100% width of screen size. Previously I have shared a CSS blockquote design, this is also a blockquote but this time it’s about full width.

Today you will learn to create a flexible paragraph with the screen’s full width. This is responsive design these texts will fit on any screen size, you can see also live transformation if you resize the window slowly. This font resize function is created using JavaScript. You can use this program on your review section, quote section, etc.

So, Today I am sharing Responsive Full Width Text With CSS and JavaScript. In other words, Flexible Text Block or Paragraph quote. I have used normal HTML CSS & JavaScript, I did not use any library for creating that. I think you should know this technique to create flexible texts. This program is very easy to understand, nothing is difficult here. If you have basic knowledge of JS then you can get it easily.

If you are thinking now how this Responsive Text Block actually is, Then see the preview given below.

Preview Of Flexible Text Block With 100% Width

See this video preview to getting an idea of how this program looks like.

Now you can see this visually. If you like this, Then get the source code of its.

Responsive Full Width Text With CSS and JavaScript Source Code

Before sharing source code, Let’s talk about it. As you know I have used JavaScript mostly to create this. Basically, I have created an HTML Blockquote and put every line in a separate span. Also with this, I have created another span with a different class for command & full stop.

In the CSS section, First I have put 100vh of height. After that, I have put other properties for the font family,grid display, etc. With JavaScript, I have created 2 variables for text and special characters like comma, full stop. The main thing is in the javascript files is put the size of the font. For this, I have divided 120 by text length (info), The code looks like this: elem.style.fontSize = 120 / elem.innerHTML.length + "vw"

You will understand fully after getting the codes because codes are easy to understand. For creating this full width text program you have to create 3 files. First for HTML, second for CSS, & third for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given here below.

<!DOCTYPE html>
<html lang="en" >
<!--Code By Webdevtrick ( https://webdevtrick.com )-->
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Full-Width Text | Webdevtrick.com</title>
  <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">
      <link rel="stylesheet" href="style.css">
  
</head>
 
<body>
  <blockquote class="block">
    <span class="texts">Success is no accident</span><span class="append">.</span>
    <span class="texts">It is hard work</span><span class="append">,</span>
    <span class="texts">learning, studying, sacrifice</span>
    <span class="texts">and most of all</span><span class="append">,</span>
    <span class="texts">love of what</span>
    <span class="texts"> you are doing</span>
    <span class="texts">or learning to do</span><span class="append">.</span>
    <cite>
	    <span class="texts"> —Pele</span>
		</cite>
  </blockquote>
  
  <script  src="function.js"></script>
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes.

/** Code By Webdevtrick ( https://webdevtrick.com ) **/
body {
  display: flex;
  font-family: 'Lato', sans-serif;
  margin: 0;
  min-height: 100vh;
}
 
cite {
  font-stretch: condensed;
  font-style: normal;
  font-weight: bold;
}
 
.block {
  display: grid;
  grid-template-columns: max-content 1fr;
  margin: auto;
  text-transform: uppercase;
  width: max-content;
}
 
.texts,
.block cite {
  display: flex;
  grid-column: 1;
  justify-content: space-between;
}

function.js

The final step, Create a JavaScript file named ‘function.js‘ and put the codes.

/** Code By Webdevtrick ( https://webdevtrick.com ) **/
var lines = document.querySelectorAll(".texts");
var appendages = document.querySelectorAll(".append");
 
var wrapCharacters = function(lines) {
  return lines.forEach(function(line) {
    var characters = line.innerHTML.split("");
    var wrappedCharacters = characters
      .map(function(character) {
        if (character === " ") {
          return '<span class="texts">&nbsp;</span>';
        }
        return '<span class="texts">' + character + "</span>";
      })
      .join("");
    return (line.innerHTML = wrappedCharacters);
  });
};
 
var useSiblingFontSize = function(elem) {
  elem.style.fontSize = elem.previousSibling.style.fontSize;
};
 
var setFontSize = function(elems) {
  return elems.forEach(function(elem) {
    if (!elem.classList.contains("append")) {
      return (elem.style.fontSize = 120 / elem.innerHTML.length + "vw");
    }
    return useSiblingFontSize(elem);
  });
};
 
var formatTextBlocks = function() {
  setFontSize(lines);
  setFontSize(appendages);
  wrapCharacters(lines);
};
 
formatTextBlocks();

That’s It. Now you have successfully created Responsive Full Width Text With CSS and JavaScript, Flexible Text Block with 100% screen width.

If you liked this post, share it with all of your programming buddies! Thank you!

Further reading


Originally published on https://webdevtrick.com