HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<h1>CSS attr() polyfill</h1>
<p> This polyfill makes it possible to use <code>attr()</code> like it is defined in the <a href="http://www.w3.org/TR/2013/CR-css3-values-20130730/#attr">spec</a>.
You can drag the sliders to manipulate the data-attributes. <s>In Google Chrome you will get instand feedback.</s> Firefox will wait till the user interaction is finished, than the MutationObserver kicks in.</p>
<h2>Demos</h2>
<h3>Simple Demo</h3>
<div class="demo1" id="js-demo1" data-width="100" data-height="100"></div>
<pre class="demoContainer container-html ">
<div class="demo1" data-width="<input class="slider js-slider" data-target="js-demo1" data-attr="data-width" type="range" min="50" max="200" value="50"/>" data-height="<input class="slider js-slider" data-target="js-demo1" data-attr="data-height" type="range" min="50" max="200" value="50"/>">
</pre>
<pre>
<style class="demoContainer container-styles js-demo1">
.demo1{
width:attr(data-width px);
height:attr(data-height px);
display:block;
background:green;
}
</style>
</pre>
<h3>Advanced Demo</h3>
<div class="demo2" id="js-demo2" data-bg-rotation="0"></div>
<pre class="demoContainer container-html">
<div class="bar" data-bg-rotation="<input class="slider js-slider" data-target="js-demo2" data-attr="data-bg-rotation" type="range" min="0" max="360" value="50"/>">
</pre>
<pre>
<style class="demoContainer container-styles js-demo2">
.demo2{
background:linear-gradient(attr(data-bg-rotation deg), blue, green);
background:-webkit-linear-gradient(attr(data-bg-rotation deg), blue, green);
display:block;
width:100px;
height:100px;
}
</style>
</pre>
<h3 id="calc">Combine with native calc()</h3>
<div class="demo3" id="js-demo3" data-addition="50"></div>
<pre class="demoContainer container-html">
<div class="bar" data-addition="<input class="slider js-slider" data-target="js-demo3" data-attr="data-addition" type="range" min="0" max="100" value="50"/>">
</pre>
<pre>
<style class="demoContainer container-styles js-demo3">
.demo3{
height:50px;
width:calc( 10px + attr(data-addition px));
background:green;
display:block;
}
</style>
<pre>
.demoContainer{
position:relative;
display:block;
border-radius:5px;
}
.demoContainer:before{
position:absolute;
top:5px; right:5px;
font-family: sans-serif;
font-size:12px;
}
.container-html{
border:1px solid darkblue;
background:lightblue;
padding:2em 0 2em 0;
}
.container-html:before{
content:'HTML';
}
.container-styles{
border:1px solid darkgreen;
background:lightgreen;
}
.container-styles:before{
content:'CSS';
}
body{
font-family:sans-serif;
}
.slider{
display:inline-block;
vertical-align:middle;
width:50px;
}
/*! CSS3 attr() Polyfill - v0.0.2 - 2013-08-16
*
* Copyright (c) 2013 Fabrice Weinberg
*/
;(function (exports){
function PropertyValueParser(){ }
PropertyValueParser.prototype = {
/**
* This function will convert CSS Propertys like:
* "border-raidus" to "borderRadius" or
* "-webkit-transform" to "webkitTransform"
*/
hyphenToCamelCase : function (property) {
// Is there a hyphen?
if (property.indexOf('-') === -1) return property;
// Take care of the - for vendor prefixes
if (property.charAt(0) === '-') property = property.substr(1);
var spl = property.split('-'),
result = '',
length = spl.length;
for (var i = 1; i < length; i++) {
var w = spl[i];
// First letter in uppercase rest in lowercase
result += w[0].toUpperCase() + w.substr(1).toLowerCase();
}
return spl[0].toLowerCase()+result;
},
parseParam : function(params){
var spaceStart = params.indexOf(' '),
commaStart = params.indexOf(','),
attrName = '',
unit = '',
fallback = '';
if (spaceStart !== -1) {
attrName = params.substr(0, spaceStart).trim();
if (commaStart !== -1) {
unit = params.substr(spaceStart + 1, commaStart - (spaceStart + 1)).trim();
} else {
unit = params.substr(spaceStart + 1).trim();
}
}
if (commaStart !== -1) {
fallback = params.substr(commaStart + 1).trim();
}
// If attr is not yet set params must be the attrName;
if (attrName === ''){
attrName = params;
}
return [attrName, unit, fallback];
},
parse : function(property, value){
if (!property || !value) return null;
var result = [],
attr = [],
last = 0,
i = 0,
funcStart,
funcEnd;
// Simple check to see if there is a valid function statement.
if ( value.indexOf('(') !== -1 && value.split("(").length === value.split(")").length) {
// Search for the attr( function
while ((i = value.indexOf("attr(", last)) !== -1) {
funcStart = i + 5; // Add 5 for attr(
funcEnd = value.indexOf(")", funcStart);
// Add letters between each attr() occurence
if (i - last !== 0)
result.push('"' + value.substr(last, i - last) + '"');
// Parse attr() function for paramater
var param = this.parseParam(value.substr(funcStart, funcEnd - funcStart));
if (param[0] === '') return null; // Empty attr() function
// Translate it to Javascript
result.push('(n.hasAttribute("' + param[0] + '") ? (n.getAttribute("' + param[0] + '") + "' + param[1] + '") : "' + param[2] + '" + "' + param[1] + '")');
// Add the Attribute to the attrCache
attr.push(param[0]);
last = ++funcEnd;
}
if (last > 0){
// Add the remaining string after the last attr() function
result.push('"' + value.substr(last) + '"');
return {
// Build new JavaScript Function
func : new Function('n', 'return ' + result.join('+')),
attr : attr,
cssProp : this.hyphenToCamelCase(property)
};
}
}
return null;
}
};
var CSSParser = (function(propertyValueParser){
var push = [].push,
cssRule = /\s*(.*?)\s*{([^}]*)}/g,
cssParse = /\s*(.*?)\s*:\s*([^;]*?);/g;
function CSSParser() { }
CSSParser.prototype = {
parse : function (css) {
if (css === undefined) return {};
css = css.replace(/(?:\r|\n)/g, '').replace(/\/\*.+?\*\//g, '').toLowerCase();
var ruleMatch, propMatch, cssExtendedFunction = {};
while ((ruleMatch = cssRule.exec(css)) !== null) {
var selector = ruleMatch[1],
body = ruleMatch[2];
while ((propMatch = cssParse.exec(body)) !== null) {
var parsedCssValue = propertyValueParser.parse(propMatch[1], propMatch[2]);
// Ignore 'Content' css property.
if (parsedCssValue !== null && parsedCssValue.cssProp !== 'content') {
var selectorData = cssExtendedFunction[selector] || {
attr: {},
filter: []
};
// Add dataAttr to filter
push.apply(selectorData.filter, parsedCssValue.attr);
// Add cssFunc to each dataAttr in selectorData;
parsedCssValue.attr.forEach(function (i) {
selectorData.attr[i] = (selectorData.attr[i] || []);
selectorData.attr[i].push(parsedCssValue);
});
cssExtendedFunction[selector] = selectorData;
}
}
}
return cssExtendedFunction;
}
};
return CSSParser;
})(new PropertyValueParser());
function StyleGenerator(doc){
this.doc = doc;
}
StyleGenerator.prototype = {
resolveFuncList : function (node, styles, cssPropValueList) {
var result, attrFunc;
for (var i = 0; i < cssPropValueList.length; i++) {
var value = cssPropValueList[i];
styles[value.cssProp] = value.func(node);
}
},
generate : function (ast) {
var styleMap = [];
for (var selector in ast) {
var nodeList = this.doc.querySelectorAll(selector),
selectorData = ast[selector];
for (var i = 0; i < nodeList.length; i++) {
var node = nodeList[i],
styles = {},
styleMapForNode = {
node : node,
styles: styles
};
for (var dataAttr in selectorData.attr) {
var cssPropValueList = selectorData.attr[dataAttr];
this.resolveFuncList(node, styles, cssPropValueList);
}
styleMap.push(styleMapForNode);
}
}
return styleMap;
},
apply : function (styleMap) {
// Write styles to node.
for (var i = 0; i < styleMap.length; i++) {
var styleForNode = styleMap[i],
node = styleForNode.node,
styles = styleForNode.styles;
for (var prop in styles) {
node.style[prop] = styles[prop];
}
}
}
};
function NodeObserver(observerList, mutationObserver, styleGenerator, doc){
this.observerList = observerList;
this.mutationObserver = mutationObserver;
this.styleGenerator = styleGenerator;
this.doc = doc;
}
NodeObserver.prototype = {
remove : function () {
this.observerList.forEach(function (observer) {
observer.disconnect();
});
},
add : function (node, attr, filter) {
var styleGenerator = this.styleGenerator;
var observer = new this.mutationObserver(function (mutationList) {
var styles = {},
styleMap = [{
node: node,
styles: styles
}];
for (var i = 0; i < mutationList.length; i++) {
var mutation = mutationList[i],
attrName = mutation.attributeName;
if (node.getAttribute(attrName) !== mutation.oldValue) {
styleGenerator.resolveFuncList(node, styles, attr[attrName]);
}
}
styleGenerator.apply(styleMap);
});
observer.observe(node, {
attributes: true,
attributeOldValue: true,
attributeFilter: filter
});
return observer;
},
attach : function (ast) {
for (var selector in ast) {
var nodeList = this.doc.querySelectorAll(selector),
selectorData = ast[selector];
for (var i = 0; i < nodeList.length; i++) {
var node = nodeList[i];
this.observerList.push(this.add(node, selectorData.attr, selectorData.filter));
}
}
}
};
exports.cssattr = (function(cssParser, styleGenerator, nodeObserver){
return {
parse: function (css) {
this.cssAst = cssParser.parse(css);
return this;
},
show: function () {
styleGenerator.apply(styleGenerator.generate(this.cssAst));
return this;
},
observe: function () {
nodeObserver.attach(this.cssAst);
return this;
},
unobserve: function () {
nodeObserver.remove();
return this;
}
};
})( new CSSParser(),
new StyleGenerator(document),
new NodeObserver([], MutationObserver || WebKitMutationObserver,
new StyleGenerator(document), document) );
})(window);
// Get all demo styles
var styleNode = document.querySelectorAll('.container-styles'),
css = '';
for (var i = 0; i < styleNode.length; i++) {
css += styleNode[i].innerHTML;
}
// Parse the CSS, show the result and observe for changes;
cssattr.parse(css).show().observe();
var sliderList = document.querySelectorAll('.js-slider');
for (var i=0;i<sliderList.length;i++){
var slider = sliderList[i],
target = document.querySelector('#'+slider.getAttribute('data-target')),
attrName = slider.getAttribute('data-attr');
slider.onchange = (function(attrName, target){
return function (){
target.setAttribute(attrName, this.value);
}
})(attrName, target);
}
Also see: Tab Triggers