JSPM

  • Created
  • Published
  • Downloads 10
  • Score
    100M100P100Q68378F
  • License MIT

Harness the power of JavaScript in your stylesheets with Als-Simple-CSS. Easily manage, construct, and manipulate dynamic CSS stylesheets at runtime. Enjoy enhanced readability with extensive property shortcuts and more.

Package Exports

  • als-simple-css
  • als-simple-css/simple.js
  • als-simple-css/simple.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (als-simple-css) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Als-Simple-Css 7

Built from scratch

Simple CSS is a powerful JavaScript library that allows developers to construct and manage CSS stylesheets dynamically with JS.

Features

  • JavaScript-Powered: With Simple CSS, your stylesheet is a JavaScript object. You get all the power of JavaScript - variables, loops, conditionals - to use in your styles.
  • Dynamic Stylesheet Management: Simple CSS allows you to add, modify, and manipulate your styles at runtime, creating interactive and responsive stylesheets.
  • Shortcuts for Common Styles: Shortcuts for frequent CSS properties are readily available in Simple CSS, making your style definitions compact and easy to read.
  • Automated Conversion: The library automatically converts JavaScript style definitions to CSS, handling even tricky parts like camelCase to kebab-case conversion, and much more.
  • Utility Methods: Simple CSS comes with a range of utility methods for common operations like determining color luma, checking if a color is dark, or creating color shades.
  • Error Handling: The library includes error checking and handling to ensure your stylesheets are always valid and bug-free.
  • Lightweight: Simple CSS is lightweight and has no dependencies, making it an easy addition to any project.

Install, import and basic usage

For instalation:

npm i als-simple-css

Use in browser:

<script src="/node_modules/als-simple-css/simple.js"></script>

Use as commonjs:

const Simple = require('als-simple-css')

Use as module:

import Simple from 'als-simple-css/simple.mjs'

Syntax Overview

The Simple class in the Simple CSS library works with an array of style objects. Each object represents a CSS rule set, media query, or keyframe definition.

Let's break down how to define styles using Simple CSS:

  1. Basic Selectors You start by defining a JavaScript object where the key is the CSS selector and the value is another object representing properties and their values. Here is the template for a basic selector:
const simple = new Simple({
   selector: {
      'another-property': 'another-value'
      propertyName: 'property-value',
   }
})

You can use camelCase property name (like it works in element.style) in addition to kebab-case. Like borderWidth instead border-width.

Example:

const simple = new Simple({
  body: {
    backgroundColor: 'black',
    color: 'white'
  }
})
  1. Media Queries To define a media query, you use a key-value pair where the key is the full media query string and the value is an array of style objects that should apply under that media query. The format is as follows:
{ '@media query': [ /* array of style objects */ ] }

Example:

{
  '@media (max-width:800px)': [
    {
      '.some': {
        'font-size': '14px',
        'line-height': '1.5'
      }
    }
  ]
}
  1. Keyframes

Similar to media queries, keyframes are represented as a key-value pair, where the key is @keyframes animationName and the value is an array of style objects representing the keyframe selectors (like '0%', '100%') and their corresponding style rules:

{
  '@keyframes animationName': [
    {
      '0%': {
        /* styles */
      },
      '100%': {
        /* styles */
      }
    }
  ]
}

Example:

{
  '@keyframes slide': [
    {
      '0%': {
        'transform': 'translateX(0)'
      },
      '100%': {
        'transform': 'translateX(100px)'
      }
    }
  ]
}

Once you have defined your styles, you create a new instance of the Simple class and pass the styles array to the constructor. After that, you can either publish the styles to the browser using the publish() method, or retrieve the raw stylesheet using the stylesheet() method.

Example:

const styles = [ /* your styles here */ ];

const simple = new Simple(styles);

// Publish the styles to the browser:
simple.publish();

// Or retrieve the raw stylesheet:
const rawStyles = simple.stylesheet(true);

In the raw stylesheet method, passing true minifies the output.

Property Shortcuts

In addition to the main syntax, the Simple class also provides an extensive list of property shortcuts. These are shortened representations of common CSS properties, designed to make your styles more concise and easier to write.

For example, instead of writing 'background-color': 'red', you can use the bgc shortcut:

{
  body: {
    bgc: 'red'
  }
}

Below are all the available shortcuts and their corresponding CSS properties:

Shortcut CSS Property
a animation
bgc background-color
c color
bg background
bgi background-image
b border
br border-right
bl border-left
bt border-top
bb border-bottom
bc border-color
brc border-right-color
blc border-left-color
btc border-top-color
bbc border-bottom-color
bs border-style
brs border-right-style
bls border-left-style
bts border-top-style
bbs border-bottom-style
bw border-width
brw border-right-width
blw border-left-width
btw border-top-width
bbw border-bottom-width
radius border-radius
o outline
oc outline-color
os outline-style
ow outline-width
maxw max-width
minw min-width
h height
w width
maxh max-height
minh min-height
of overflow
ofx overflow-x
ofy overflow-y
scrollb scroll-behavior
p padding
m margin
pr padding-right
pl padding-left
pt padding-top
pb padding-bottom
mr margin-right
ml margin-left
mt margin-top
mb margin-bottom
d display
flexw flex-wrap
flexg flex-grow
flexdir flex-direction
ai align-items
ac align-content
jc justify-content
gcols grid-template-columns
grows grid-template-rows
gacols grid-auto-columns
garows grid-auto-rows
areas grid-template-areas
area grid-area
dir direction
textt text-transform
ta text-align
td text-decoration
ws white-space
ww word-wrap
ff font-family
to text-overflow
ls letter-spacing
lh line-height
wb word-break
fv font-variant
fs font-size
fw font-weight
fstyle font-style
f font
pos position
z z-index
tr transform
cur cursor

Adding custom shortcuts

You can easily add your own shortcuts, by adding second parameter to constructor.

Here is the example:

const shorts = {
   aic:'animation-iteration-count',
   atf:'animation-timing-function'
}
const styles = [
   {'.some':{
      aic:'3',atf:'linear'
   }}
]
const simple = new Simple(styles,shorts)
console.log(simple.stylesheet())

The output:

.some {
   animation-iteration-count:3;
   animation-timing-function:linear
}

Variables

You can use css variables as is or to use shorter syntax as shown below:

  • {$varname:'value'} equivalent to --varname:value
  • $varname(value) equivalent to var(--varname,value)
  • $varname equivalent to var(--varname)

Example:

let styles = [
   {":root":{$w:'50px'}}, // --w:50px
   {".some": {width:'$w'}}, // width:var(--w)
   {".some1": {height:'$h(50px)'}} // height:var(--h,50px)
]

!important

By using ! in property's value, you add !important.

For example:

let styles = [
   {'.test':{color:'red'}},
   {'.test':{color:'green !'}},
]

Comments and Charset Declarations

With Simple CSS, you can insert comments or any other string such as charset declarations into your styles array. These are inserted as separate string items in the array.

For instance, if you want to add a comment, you can include it as a string in the styles array, like this:

const styles = new Simple([
   {'.test':{c:'red'}},
   '/*comment*/',
   {'.test2':{c:'green'}},
])

Similarly, you can add a charset declaration to the stylesheet. For example, if you want to specify UTF-8 as the charset, you can do so as follows:

const styles = new Simple([
   '@charset "UTF-8";',
   {'.test':{c:'red'}},
   {'.test2':{c:'green'}},
])

When you call styles.publish() or styles.stylesheet(), the comment or charset declaration will be included in the resulting CSS.

Selector links are a powerful feature of the Simple class that enables you to create relationships between different selectors. This functionality allows you to apply shared styles across multiple selectors and can be particularly useful when handling pseudo-classes, such as :hover.

In the Simple class, you use the $ character followed by a number to denote a link to a previous selector. For example, $1 refers to the first selector defined in your styles, $2 to the second, and so on.

Consider this example:

const styles = new Simple([
   {'.test':{c:'red'}},
   {'.test2':{c:'green'}},
   {'$1:hover,$2:hover':{c:'black'}}
]);

In this case, $1 refers to .test and $2 refers to .test2. So, the third line is equivalent to .test:hover,.test2:hover.

The resulting CSS after invoking styles.publish() or styles.stylesheet() would be:

.test {
    color:red
}
.test2 {
    color:green
}
.test:hover, .test2:hover {
    color:black
}

This feature greatly simplifies the management of shared styles and reduces redundancy in your code, making it easier to read and maintain. Remember that the order of the selectors is crucial as the link refers to the position in the array, starting from 1.

Additional Tools

shade and isDark

With Simple.shade you can get css color code for lighter or darker color.

Syntax: shade(hex, percent,opacity)

new Simple([
   {'.blue':{bgc:'#5F9EA0'}},
   {'.blue1':{bgc:Simple.shade('#5F9EA0',40)}}, // 40% lighter
   {'.blue2':{bgc:Simple.shade('#5F9EA0',-40)}}, // 40% darker
   {'.blue3':{bgc:Simple.shade('#5F9EA0',30,0.2)}}, // 30% lighter and 20% opacity 
])

With Simple.isDark you can check if hex rgb color is dark.

Here is example:

let textColor = 'black'
if(Simple.isDark('#080808')) textColor = 'white'

Luma

Luma is a score between 0 and 255, where 0 is black and 255 is white.

let textColor = 'black'
if(Simple.luma('#080808') < 40 ) textColor = 'white'

Variable Management

You can manage global css variables with Simple.$(varName,varValue,varValue2) method. Here how it works:

Simple.$('w') // return 50px
Simple.$('w','100px') // Changing --w to 100px
Simple.$('w','100px','50px') // if w=50px, change to 100px. If w=100px, change to 50px. Else - do nothing. 

Here is the example of usage:

<script>
new Simple([
   {":root": {$d:'none'}},
   {".block": {d:'$d'}},
])
</script>

<button onclick="Simple.$('d','none','block')">Hide/show</button>
<div class="block">Hello</div>