CSS/JS - Exploring More

Exploring more ways to write CSS with JS

I still write a lot of just vanilla JS and CSS. But, with React and Vue development, I have found that I have been ok with breaking some of my habits and setting up documents in a new way.

I was researching some different ways to work with CSS and JS and found a few different frameworks. Some of them looked like they were framework free and some of them looked like they wanted to use React. If you are interested here are the ones that I wanted to look at.

For, this experiment I wanted to make something that would allow me to set some variables and then inject some html to an empty div in the main document. I didn’t want to use any frameworks.

First, I set up and object with some values to use later.

var cssVars = {
	babyBlue:'rgba(44, 118, 238, 0.1)',
	red: '#f53e53',
	dgray:'#969696',
	paddingX:'7px',
	paddingY:'10px',
	baseFontSize:'1rem',
	borderRadius:'15px',
};

Then, lets setup some css to add to our document as well. I wanted to style the body as well as a button that we are going to inject later. If you look below you can see how we are using our object to insert values into this block of CSS.

const cssJS = `
  body {
		background: ${cssVars.babyBlue};
	}
  .btn {
	padding: ${cssVars.paddingY} ${cssVars.paddingX};
	font-size: ${cssVars.baseFontSize};
	border-radius: ${cssVars.borderRadius};
	color: white;
	background-color: ${cssVars.red};
  }
`;

Next, lets get a button setup just so we have something to play with.

const button = `
	<button class="btn">CSS/JS Button</button>
`;

You can look at the codepen below to see the final result. We injected our CSS block first and then we attached our button html. I was a bit skeptical at first but I did like it once I got into it. I feel like from a maintenance prospective this would be a nightmare but I think I need to take one of those frameworks into a production app to really see.

Published by and tagged css, cssinjs and js using 338 words.