<div>Example Element</div>CSS value serialization / notebook
CSS value serialization
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
div {
position: absolute; /* keyword */
rotate: 1rad; /* <angle> */
color: hsl(240 50% 50%); /* <color> */
background-color: hsl(120 50% 50% / 0.3); /* <color> with alpha */
border-color: lab(10 -120 -120); /* <color> in non-sRGB space */
margin: 2em; /* relative <length> */
padding: 2cm; /* absolute <length> */
font-size: calc(1em + 2px); /* complex expression */
left: 50%; /* <percentage> */
animation-duration: 500ms; /* <time> */
}const element = document.querySelector("div");
const table = document.createElement("table");
const elemStyle = getComputedStyle(element);
const ruleStyle = document.getElementById("css-output").sheet.cssRules[0].style;
const head = table.createTHead().insertRow();
["Property", "getComputedStyle()", "CSSStyleRule"].forEach((text) => {
const th = document.createElement("th");
th.textContent = text;
head.appendChild(th);
});
for (const property of [
"position",
"rotate",
"color",
"background-color",
"border-color",
"margin",
"padding",
"font-size",
"left",
"animation-duration",
]) {
const row = document.createElement("tr");
const propCell = document.createElement("td");
const valueCell = document.createElement("td");
const ruleCell = document.createElement("td");
propCell.textContent = property;
valueCell.textContent = elemStyle.getPropertyValue(property);
ruleCell.textContent = ruleStyle.getPropertyValue(property);
row.appendChild(propCell);
row.appendChild(valueCell);
row.appendChild(ruleCell);
table.appendChild(row);
}
document.body.appendChild(table);<div class="example hsl">HSL Color</div>
<div class="example lab">LAB Color</div>
<div class="example named">Named Color</div>
<div class="example alpha">Transparent Color</div>
<pre id="output"></pre>.example {
padding: 10px;
margin: 5px;
color: white;
}
.hsl {
background-color: hsl(240 50% 50%);
}
.lab {
background-color: lab(100% 0 0);
}
.named {
background-color: blue;
}
.alpha {
background-color: hsl(120 50% 50% / 0.3);
}const examples = document.querySelectorAll(".example");
const output = document.getElementById("output");
examples.forEach((element) => {
const style = getComputedStyle(element);
output.textContent += `${element.className}: ${style.getPropertyValue("background-color")}\n`;
});element.style.marginLeft = "2em";
console.log(getComputedStyle(element).marginLeft);
// "32px" (depending on font size)