Package Exports
- als-simple-css
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
Simple.css
link to old version documentation site
If you have any suggestions, please notice me on AlexSorkin1980@gmail.com
About
If you write css code, you familiar with this long slim code and those long properties names. Also you probably familiar with not comfortable way to use variables in css and missing ability to include one style in another.
Meet simpler way to write css and manage variables.
Simple.css is a fast, short, simple and easy way to write css code using JavaScript. And the best part, that the code above can be simply generated to css code.
Advantages:
- Significantly shorter code
- Easy use and manipulate css variables with JS
- Bind one style inside another
- Convert to regular css file and watch changes (via node)
- Drag elements, manipulate classes, styles and attributes and zIndex
- Use media queries with JS depend on screen size
Sketch.css
The 1.2 version includes sketch.css. Sketch.css is css framework, which includes simple.css styles. Documentation site available on: http://sketch.simple-css.com/.
cdn link: https://cdn.jsdelivr.net/npm/als-simple-css@1.2.0/sketch.js
To use sketch.css, just include the sketch.js after simple.js
install
Install the package in console
npm i als-simple-css
Include the simple.js in your project in head section.
<head>
<script src="node_modules/als-simple-css/simple.js"> </script>
</head>
cdn
You can use cdn link: https://cdn.jsdelivr.net/npm/als-simple-css@1.1.1/simple.js
<head>
<script src="https://cdn.jsdelivr.net/npm/als-simple-css@1.1.1/simple.js"> </script>
</head>
Basics
As in regular css, you can insert css code:
- As a file (js file instead css)
- Inside html code (inside instead inside )
- Inside dom element (as
css=""
insteadstyle=""
)
Styles inside html or file
In both cases you will use the _(styles:object)
function. Styles is an object which incudes selectors and properties.
Here is an example for class .test
with padding .5em
and text size 16px
:
<head>
<script src="node_modules/als-simple-css/simple.js"> </script>
<script>_({".test":"p-.5em ts-16px",})</script>
</head>
Important
The script has to be in head section, before dom content loaded and after including simple.css.
You can do the same inside js file and just include this file as <script src="styles.js">
The _
function will create <style>
tag and will add vonverted css styles to it.
Here the syntax of the function:
Basic syntax for styles:
_({
"selector": "pseudoClass:property-parameter_parameter"
})
Basics in syntax
- "-" = ":"
- "_" = " " (space)
- "--" = "-" or camelCase
- "!" = !important
Examples:
/* Css syntax */
* {font-family: Arial, Sans-serif;}
// Simple.css syntax - few options which do the same
_({
"*":"fontFamily-arial,sansSerif", // camelCase instead "-"
"*":"fontFamily-arial,sans--serif", // "--" insted "-"
"*":"ff-arial,sansSerif", // camelCase instead "-" and short property name
})
As shown on example above, there are few options to write code. You can use short property names (the list will be shown below) or full property names. Also, you need to use "_" instead space, "-" instead ":" and "--" or camelCase instead "-".
For example borderRightColor-red
, brc-red
and border--right--color-red
do the same. First example is camelCase, second - short property and third using "--" insted "-".
For example, instead
.btn {
padding:.5rem 1rem;
outline:0;
border:0;
cursor: pointer;
background-color:blue;
color:white;
font-size:1rem;
}
.btn:hover {
background-color:lightblue;
color:black;
}
.btn:focus {
font-weight: bold;
}
You can write:
_({
".btn":`p-.5rem_1rem o-0 b-0 pointer bgc-blue
tc-white ts-1rem h:bgc-lightblue h:tc-black f:bold`
})
It shorter and more readble. For example "p" is padding, "o" is outline, "bgc" is background-color. But don't worry. You don't need to learn the short names. You can use regular css inside Simple.css function, with a little bit different syntax. It may looks like this:
_({
".btn":`padding-.5rem_1rem outline-0 b-0 cursor-pointer
backgroundColor-blue color-white fontSize-1rem
h:backgroundColor-lightblue h:fontColor-black f:fontWeight-bold`
})
Styles inside dom element
As mentioned before, you can use simple.css inside dom elements. Instead to add style=""
, add css=""
and simple.css will convert the simple.css into style's attribute value.
As in a regular style inside dom element, inside css="" you can`t define variables and use pseudo classes and elements.
Here is the example:
<button css="p-.5rem_1rem o-0 b-0 pointer
bgc-blue tc-white ts-1rem">click</button>
After page will be loaded, it will look like this:
<button style="padding:.5rem 1rem; outline:0; border:0; cursor: pointer;
background-color:blue; color:white; font-size:1rem; ">click</button>
Box sizing
By default, simple.css add *, *::before, *::after {box-sizing: border-box;}
to styles.
If you want to disable it, you need to define _boxSizing = false
before simple.js script.
<head>
<!-- <script>window._boxSizing = false;</script> -->
<script src="node_modules/als-simple-css/simple.js"> </script>
</head>
List of short properties
All short properties included inside object _propRules
.
You can easily add, remove and change this object. For example, you can add your color, size, or anything you want. The new property has to folow the rules:
- It can be only with lowercases
- It can be
property
,property:value
orproperty:function(
- It has to be without spaces One thing is important, you need to do this before you running _() function. Here is the example:
_propRules['textXl'] = 'font-size:large'
List of included short properties:
{
Background: {
bg: "background",
bgc: "background-color",
bglg: "background-image:linear-gradient(",
bgrlg: "background-image: repeating-linear-gradient(",
bgrg: "background-image: radial-gradient(",
bgrrg: "background-image: repeating-radial-gradient(",
bgs: "background-size",
bgo: "background-origin",
bgclip: "background-clip",
bgi: "background-image",
bgr: "background-repeat",
bga: "background-attachment",
bgp: "background-position",
},
Borders: {
b: "border",
br: "border-right",
bl: "border-left",
bt: "border-top",
bb: "border-bottom",
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",
bc: "border-color",
brc: "border-right-color",
blc: "border-left-color",
btc: "border-top-color",
bbc: "border-bottom-color",
radius: "border-radius",
tlradius:"border-top-left-radius",
trradius:"border-top-right-radius",
brradius:"border-bottom-right-radius",
blradius:"border-bottom-left-radius",
},
Margins: {
m: "margin",
mb: "margin-bottom",
ml: "margin-left",
mr: "margin-right",
mt: "margin-top",
},
Padding: {
p: "padding",
pb: "padding-bottom",
pl: "padding-left",
pr: "padding-right",
pt: "padding-top",
},
"Height and width": {
h:"height",
w:"width",
maxh:"max-height",
minh:"min-height",
maxw:"max-width",
minw:"min-width",
},
Outline: {
o:"outline",
oc:"outline-color",
oo:"outline-offset",
os:"outline-style",
ow:"outline-width",
},
Text: {
tc: "color",
td: "text-decoration",
to: "text-overflow",
ta: "text-align",
tcenter: "text-align:center",
tleft: "text-align:left",
tright: "text-align:right",
tjustify: "text-align:justify",
tclip: "text-overflow:clip",
tellipsis: "text-overflow:ellipsis",
underline: "text-decoration:underline",
overline: "text-decoration:overline",
linet: "text-decoration:line-through",
tt: "text-transform",
dir:"direction",
rtl:'direction:rtl',
ltr:'direction:ltr',
ub: "unicode-bidi",
ti: "text-indent",
ls: "letter-spacing",
lh: "line-height",
ws: "word-spacing",
wb: "word-break",
space: "white-space",
nowrap: "white-space:nowrap",
pre: "white-space:pre",
prewrap: "white-space:pre-wrap",
preline: "white-space:pre-line",
breaks: "white-space:break-spaces",
ww: "word-wrap",
ts: "font-size",
},
Font: {
f: "font",
ff: "font-family",
fs: "font-style",
tw: "font-weight",
fv: "font-variant",
italic: "font-style: italic",
bold: "font-weight: bold",
arial: "font-family: Arial",
verdana: "font-family: Verdana",
helvetica: "font-family: Helvetica",
tahoma: "font-family: Tahoma",
trebuchet: "font-family: Trebuchet MS",
times: "font-family: Times New Roman",
georgia: "font-family: Georgia",
garamond: "font-family: Garamond",
courier: "font-family: Courier New",
brush: "font-family: Brush Script MT",
},
Lists: {
list: "list-style",
listi:"list-style-image",
listp:"list-style-position",
listt:"list-style-type",
},
Display: {
d: "display",
block: "display: block",
inline: "display: inline",
iblock: "display: inline-block",
flex: "display: flex",
grid: "display: grid",
iflex: "display: inline-flex",
igrid: "display: inline-grid",
hide: "display: none",
show: "display: initial",
v: "visibility",
visible: "visibility: visible",
hidden: "visibility: hidden",
},
Position: {
pos: "position",
static: "position:static",
relative: "position:relative",
fixed: "position:fixed",
absolute: "position:absolute",
sticky: "position:sticky",
clip: "clip",
rect: "clip:rect(",
z: "z-index",
},
Overflow: {
of: "overflow",
ofx: "overflow-x",
ofy: "overflow-y",
scroll: "overflow:auto",
noscroll: "overflow:hidden",
scrollx: "overflow-x:scroll",
noscrollx: "overflow-x:hidden",
scrolly: "overflow-y:scroll",
noscrolly: "overflow-y:hidden",
smooth: "scroll-behavior: smooth",
},
Float: {
float:"float",
fleft:"float:left",
fright:"float:right",
},
Flex: {
jc: "justify-content",
flexw: "flex-wrap",
flexd: "flex-direction",
flexs: "flex-shrink",
flexb: "flex-basis",
flexg: "flex-grow",
hleft: "justify-content:flex-start",
hright: "justify-content:flex-end",
hcenter: "justify-content:center",
spaceb: "justify-content:space-between",
spacea: "justify-content:space-around",
vcenter: "align-items: center",
vtop: "align-items: flex-start",
vbottom: "align-items: flex-end",
center: "justify-content:center;align-items: center",
wrap: "flex-wrap:wrap",
fcol: "flex-direction: column",
frow: "flex-direction: row",
aitems:"align-items",
acontent:"align-content",
},
Grid: {
gcol: "grid-column",
grow: "grid-row",
gcolstart: "grid-column-start",
gcolend: "grid-column-end",
gtcol: "grid-template-columns",
gtrow: "grid-template-rows",
gacol: "grid-auto-columns",
garow: "grid-auto-rows",
gtemplate: "grid-template",
gaf: "grid-auto-flow",
template: "grid-template-areas",
area: "grid-area",
gap: "gap",
rowgap: "row-gap",
colgap: "column-gap",
gaf: "grid-auto-flow",
gfcol: "grid-auto-glow:column",
gfrow: "grid-auto-glow:row",
},
Columns: {
col: "column-count",
colw: "column-width",
colr: "column-rule",
colg: "column-gap",
colspan: "column-span",
colf: "column-fill",
colrc: "column-rule-color",
colrs: "column-rule-style",
colrw: "column-rule-width",
},
Transition: {
trans: "transition",
transdelay: "transition-delay",
transduration: "transition-duration",
transprop: "transition-property",
transfn: "transition-timing-function",
},
Animation: {
a: "animation",
adelay: "animation-delay",
adir: "animation-direction",
adur: "animation-duration",
aname: "animation-name",
amode: "animation-fill-mode",
aiter: "animation-iteration-count",
aplay: "animation-play-state",
afn: "animation-timing-function",
},
Resize: {
r: "resize",
both: "resize: both",
resizeh: "resize: horizontal",
resizev: "resize: vertical",
},
Shadow: {
tshadow: "text-shadow",
shadow: "box-shadow",
},
Transform: {
translate: "transform:translate(",
rotate: "transform:rotate(",
rotatex: "transform:rotateX(",
rotatey: "transform:rotateY(",
rotatez: "transform:rotateZ(",
scalex: "transform:scaleX(",
scaley: "transform:scaleY(",
scale: "transform:scale(",
skewx: "transform:skewX(",
skewy: "transform:skewY(",
skew: "transform:skew(",
matrix: "transform:matrix(",
},
Cursors: {
c:'cursor',
pointer: 'cursor: pointer;',
move: 'cursor: move;',
hresize: 'cursor: ew-resize;',
cont: "content",
},
Effects: {
saturate: "filter: saturate(",
brightness: "filter: brightness(",
contrast: "filter: contrast(",
grayscale: "filter: grayscale(",
huer: "filter: hue-rotate(",
invert: "filter: invert(",
sepia: "filter: sepia(",
blur: "filter: blur(",
aself:'align-self',
},
}
Pseudo
You can use pseudo classes and pseudo elements with selector, but also inside the properties. See the examples below:
pseudo inside selectors
Example:
// Simple.css
_({"b::h:[test]":"cont-'hello'"})
/* Css */
[test]:hover::before {
content: 'hello';
}
You can use few selectors and add to them pseudo classes
_({"b::h:[test],div":"cont-'hello'"})
[test]:hover::before {
content: 'hello';
}
div:hover {
content: 'hello';
}
pseudo inside properties
Button example:
_({
".btn":
`p-.5rem_1rem o-0 b-0 pointer
bgc-blue tc-white ts-1rem
h:bgc-lightblue h:tc-black
f:bold`
})
Here css code for simple.css code above:
*, *::before, *::after {box-sizing: border-box;}
.btn {
padding:.5rem 1rem;
outline:0;
border:0;
cursor: pointer;
background-color:blue;
color:white;
font-size:1rem;
}
.btn:hover {
background-color:lightblue;
color:black;
}
.btn:focus {
font-weight: bold;
}
In example above, .btn has hover (h:) and focus (f:) pseudo classes which included inside properties and not inisde selector.
Here the list of pseudo classes and elements:
PseudoClasses = {
h:'hover',
f:'focus',
c:'checked',
fc:'first-child',
lc:'last-child',
d:'disabled',
a:'active',
in:'in-range',
fot:'first-of-type',
lot:'last-of-type',
i:'invalid',
l:'link',
oot:'only-of-type',
oc:'only-child',
o:'optional',
oor:'out-of-range',
ro:'read-only',
rw:'read-write',
r:'required',
t:'target',
v:'valid',
empty:'empty',
enabled:'enabled',
root:'root',
visited:'visited',
n:'not', // -selector
nc:'nth-child', // -n
nlc:'nth-last-child', // -n
nlot:'nth-last-of-type', // -n
not:'nth-of-type', // -n
lang:'lang', // -language
}
PseudoElements = {
a:'after',
b:'before',
fl:'first-letter',
fli:'first-line',
s:'selection'
}
Variables
You can easy set css variables and simply get and change their values with js.
To define variable, just add to properties $varName=value
where $varName is a name of variable and value is initial value. Here is example:
_({
'.some': "tc-$color=blue",
'.some1': "bgc-$color"
})
css result:
*, *::before, *::after {box-sizing: border-box;}
:root {
--color:blue;
}
.some {
color:var(--color);
}
.some1 {
background-color:var(--color);
}
As shown on example above, initial variable's value anyway defined in :root. But you can define all your variables in root too. Here is the example:
Example:
_({
":root": "$bg=blue",
"div": "bgc-$bg"
})
Change value for css variables with vars
Now, all your variables are available as getters and setters in vars
object variable.
vars has getter and setter for each css variable binded with _() function.
You can get value with vars.varName
or set new value with vars.$varName = 'new value'
where varName is a css variable name. Here is the example:
_({body:"$bg=blue bgc-$bg"})
console.log(vars.bg) // blue
vars.$bg = 'green' // change body color
console.log(vars.bg) // green
_$ function for change or replace css variable's value
The _$ return, change or replace value with new one.
Syntax:
_$(varName) // return varName's curent value
_$(varName,newValue) // change varName's value to newValue
_$(varName,value,value2) // If varName = value, replace with value2. If varName = value2, replace with value
Example:
<nav></nav>
<button onclick="_('v','block','none')">☰</button>
<script>_({nav:"d-$v=block"})</script>
The example above will show and hide nav menu onclick
@Media
To define media queries, use @m:condition: {selector:properties,..}
- @m: = media
- Examples:
_({
"@m:minw-600px maxw-1024px": {
div:"bg-red"
},
"@m:s & maxw-600px":{
div:"hide"
}
})
@media (max-width: 1024px) {
div {
background-color: red;
}
}
@media screen and (max-width: 600px) {
div {
display: none;
}
}
Media properties
Here the list of media properties:
MediaTypes = {
"&":" and ",
"n":" not ",
"o":" only ",
"a": "all",
"s": "screen",
"p": "print",
"sp": "speech",
"ah":"any-hover",
"ap":"any-pointer",
"ar":"aspect-ratio",
"c":"color",
"cg":"color-gamut",
"ci":"color-index",
"g":"grid",
"h":"height",
"ho":"hover",
"ic":"inverted-colors",
"ll":"light-level",
"maxar":"max-aspect-ratio",
"maxc":"max-color",
"maxci":"max-color-index",
"maxh":"max-height",
"maxm":"max-monochrome",
"maxr":"max-resolution",
"maxw":"max-width",
"minar":"min-aspect-ratio",
"minc":"min-color",
"minci":"min-color-index",
"minh":"min-height",
"minm":"min-monochrome",
"minr":"min-resolution",
"minw":"min-width",
"m":"monochrome",
"or":"orientation",
"ob":"overflow-block",
"oi":"overflow-inline",
"po":"pointer",
"r":"resolution",
"scan":"scan",
"sc":"scripting",
"u":"update",
"w":"width",
}
JS listiner for media
Simple.css has widerThen function which can run functions depend on screen width size.
Syntax:
widerThen(width,fn,fn2)
- width - screen width for listiner
- fn - run this function if screen width bigger or equal to width parameter
- fn2 - run this function if screen width smaller then width parameter
If fn and fn2 not defined, function return
- false if width<=screensize
- true if width>screensize.
Example:
let nav = document.getElementById('nav')
screenWidth(800,
// If screen width >= 800 px, hide nav
()=>{nav.style.display = 'block'}
// If screen width < 800 px, show nav
()=>{nav.style.display = 'none'},
)
is media function
isMedia is a function which checks if user agent is mobile. If user agent is mobile, function return true. Esle, return false.
isMedia()
@keyframes
Keyframes starts with @k
.
Example:
_({
"@k:test":"from:bg-red;tc-black to:bg-blue;tc-white",
})
Bind styles
You can include one style inside another. Here is an example:
_({
"[btn]":"p-.5em_1em bra-5px b-0 o-0 pointer f:bold",
"[btn-blue]":"[btn] h:bg-blue h:tc-white bg-lightblue"
})
Export to css file
You can easy export simple styles to regular css file with node.js.
Example:
// shadows.js
let _ = require('../simple/simple')
let {join} = require('path')
let filePath = join(__dirname,'test.css')
_({
"[hshadow]": "h:shadow-gray_0_0_5px_1px",
"[shadow]": "shadow-gray_0_0_5px_1px",
},filePath)
Command in console:
node shadows
Example output:
/* test.css */
*, *::before, *::after {box-sizing: border-box;}
[hshadow]:hover {
box-shadow:gray 0 0 5px 1px;
}
[shadow] {
box-shadow:gray 0 0 5px 1px;
}
Watch and convert
If you want to work only with css files, you can watch changes in your styles file and automaticly convert them to css file. The _ function return object with watch function which watching changes in your js file and convert them to css file.
let _ = require('./simple')
let styles = {"test":"ts-1rem bgc-blue m-1rem p-1rem"}
let cssFilePath = __dirname+'/test.css'
_(styles,cssFilePath).watch(__filename)
module.exports = styles
Extra
Replace and z function
The replace function __() can replace class,attribute or style and to set zIndex to dom element.
Syntax:
window._zindex
__(dom).class(class1,class2) // replace class1 to class2 or class2 to class1
__(dom).prop(prop1,prop2) // replace prop1 to prop2 or prop2 to prop1
__(dom).style(style1,style2) // replace style1 to style2 or style2 to style1
__(dom).z() // set zIndex +1
dom - dom can be or DOM element, or css selector for dom element like id, class and etc. Here few examples for dom parameter:
<!-- Exmple for DOM element -->
<button onclick="__(this)">click</button>
<!-- Exmple for css selctors -->
<input type="text" id="input">
<button onclick="__('#input')">click</button>
<button onclick="__('input')">click</button>
Replace one class with another
The class method checks which from two options are available in classList (class1 or class2) and then remove then replace the existing class with non existing.
<script>_({'.test':'tc-red','.test2':'tc-green'})</script>
<button onclick="__('#input').class('test','test2')">Change color</button>
<input type="text" id="input" class="test">
Replace props
You can replace one attribute to another with prop method. Here few examples.
Folowing example will change color to red if it's green and will change color to green if it's red.
<script>_({'[red]':'tc-red','[green]':'tc-green'})</script>
<button onclick="__('#input').prop('red','green')">Change color to green/red</button>
<input type="text" disabled id="input" red>
Folowing example, will enable the input form if it's disabled and will disable if it's not disabled
<button onclick="__('#input').prop('disabled');">Disable/Enable</button>
<input type="text" disabled id="input" test>
The value option
With prop method, you can replace attribute's value. Here is the example.
The folowing example will replace image to another, depend what image is current.
<img src="html.jpg" alt="" id="img">
<button onclick="__('#img').prop('src=html.jpg','src=styles.jpg')">change</button>
Replace style
The style has to be without spaces.
<div style="color:red;"
onclick="__(this).style('color:red','color:green')">
Hello</div>
Z index - always on top
By default simple.css creates window._zindex = 1
.
Then you call to z() function, it sets z index +1 on dom element. Thes function set element on top relative to other elements.
Drag elements
Drag function alows to make element dragble. Moreover, you can set drag triger place.
__(dom).drag(triger)
Drag method turn element's position to absolute. It necessary, to allow object move on a page. Also, drag method add mousedown and touch listiners.
Example - turning blue box to dragble.
<div css="bgc-lightblue w-100px h-100px" id="box"></div>
<script> __('#box').drag() </script>
Examle with drag triger. Now you can drag the box only with on #header place.
<div css="bgc-lightblue w-100px h-100px" id="box">
<div css="h-20px" id="header">header</div>
</div>
<script> __('#box').drag('#header') </script>