css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

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.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class='box'></div>
<nav class='rev'>
  <button class='newg'>New Gradient</button>
</nav>
<form class='rev'>
  <fieldset>
    <legend>gradient box dimensions (in <code>px</code>)</legend>
    <label for='w'>width</label>
    <input id='w' value='320' class='small'>
    <label for='h'>height</label>
    <input id='h' value='176' class='small'>
  </fieldset>
  <fieldset>
    <legend><code>linear-gradient</code> code (newest standard syntax)</legend>
    <input id='cod' value='linear-gradient(60deg, deeppink, yellow, lime)' class='large'>
  </fieldset>
  <button class='apply'>Apply!</button>
</form>
<footer class='result rev'></footer>
            
          
!
            
              * { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; background: gainsboro; }
body { font: .9em/1.5 Verdna, sans-serif; }
.box {
  /**margin: -88px -160px;/**/
  width: 320px; height: 176px;
  /**background: linear-gradient(60deg, deeppink, yellow, lime);/**/
  cursor: crosshair;
}
nav {
  position: fixed;
  z-index: 1;
  right: 0; bottom: 0; left: 0;
  border-top: solid 1px dimgrey;
  height: 72px;
}
button {
  border: 0;
  padding: .2em .65em;
	margin: .25em 1em;
	border-radius: .5em;
  box-shadow: inset 0 -1em 1em -.5em grey, 1px 1px 1px cornflowerblue;
  background: dimgrey;
  color: white;
  text-shadow: 0 -1px black;
  transition: 1s;
  cursor: pointer;
}
button:hover, button:focus {
  box-shadow: inset 0 -1em 1em -.5em black, 1px 1px 1px cornflowerblue;
  color: yellow;
}
button:focus { outline: none; }
form, .result {
  position: fixed;
  z-index: 0;
  bottom: -200px;
  border-radius: .35em .35em 0 0;
  transition: .75s;
}
form, fieldset { padding: .35em; }
form { min-width: 320px; }
fieldset {
  border: solid 1px dimgrey;
  border-radius: .35em;
  line-height: 2;
}
label, input { font: 1em monospace; }
label:after { content: ':'; }
input {
  border: solid 1px silver;
  border-radius: .25em;
}
input:focus {
  outline: none;
  box-shadow: 0 0 .3em .2em lightskyblue; }
.small {
  margin: 0 2em 0 .5em;
  width: 4em;
  text-align: right;
}
.large { width: 100%; }
.result {
  left: 50%;
  margin: 0 -2.5em;
  padding: .25em .8em;
  width: 6em;
  color: yellow;
  font: 1.2em monospace;
  text-align: center;
}
.apply { float: right; }
.revealme { bottom: 72px; }
.rev { background: black; color: whitesmoke; }
            
          
!
            
              (function(){
  var PercCalculator = function(){
    var EUtil = function() { /* utility class */
      this.setStyle = function(elStyles) {
        /*
         * elStyles is an array
         * [
         *   [element_1, {property_1_1: value_1_1, property_1_2: value_1_2}], 
         *   [element_2, {property_2_1: value_2_1}]
         *]
         */
        var t, len = elStyles.length,
  				  prefixed = {'value': ['linear-gradient']}, 
            prefixList = ['-webkit-', '-moz', '-o-'], l = prefixList.length;
        for(var i = 0; i < len; i++) {
          for(var p in elStyles[i][1]) {
            if(elStyles[i][1][p].indexOf(prefixed['value'][0]) != -1) { /* check if the value needs to be prefixed */
              t = 90 - parseInt(elStyles[i][1][p].split('(')[1].split('deg')[0], 10);
              t = prefixed['value'][0] + '(' + t + 'deg' + elStyles[i][1][p].split('deg')[1];
              for(var j = 0; j < l; j++)
                elStyles[i][0].style[p] = prefixList[j] + t;
            }
					  elStyles[i][0].style[p] = elStyles[i][1][p]; /* just set styles, no prefixes */
  				}
  			}
      };
    };
    var Line = function(point, angle) { /* Line class */
      this.getEquation = function() {
        /* 
         * Equation of a line can be written as y = a + b*x
         * The function returns the array [a, b]
        */
        return [(point.y - Math.tan(angle*Math.PI/180)*point.x), Math.tan(angle*Math.PI/180)]
      };
    };
    var getIntersection = function(line1, line2) {
      /*
       * Consider 2 lines with the equations y1 = a1 + b1*x and y2 = a2 + b2*x
       * They intersect where a1 + b1*x = a2 + b2*x
       * Which means that x = (a2 - a1)/(b1 - b2) and y = a1 + b1*(a2 - a1)/(b1 - b2)
       * The function returns the point with the x and y computed as above
      */
      var eq1 = line1.getEquation(), eq2 = line2.getEquation();
      return {'x': ((eq2[0] - eq1[0])/(eq1[1] - eq2[1])), 'y': (eq1[0] + eq1[0]*(eq2[0] - eq1[0])/(eq1[1] - eq2[1]))}
    };
    var getDistance = function(point1, point2) {
      return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
    };
    this.computePerc = function(gradData, x, y) {
      var gradLine = new Line({'x': (gradData._0PercPt.x + gradData._100PercPt.x)/2, 'y': (gradData._0PercPt.y + gradData._100PercPt.y)/2}, (gradData.angle%180 - 90)), 
          startLine = new Line({'x': gradData._0PercPt.x, 'y': gradData._0PercPt.y}, gradData.angle%180), 
          endLine = new Line({'x': gradData._100PercPt.x, 'y': gradData._100PercPt.y}, gradData.angle%180), 
          unknownLine = new Line({'x': x, 'y': y}, gradData.angle),
          _S = getIntersection(gradLine, startLine), 
          _E = getIntersection(gradLine, endLine), 
          _I = getIntersection(gradLine, unknownLine);
      if(gradData._0PercPt.x == gradData._100PercPt.x) {
        _S = gradData._0PercPt;
        _E = gradData._100PercPt;
        _I = {'x': gradData._0PercPt.x, 'y': y};
      }
      return getDistance(_S, _I)/getDistance(_S, _E);
    };
    
    this.init = function(w, h, gradCode) {
      var w = (w)?w:320, h = (h)?h:176, 
          gradCode = (gradCode)?gradCode:'linear-gradient(60deg, deeppink, yellow, lime)',
          angle = parseInt(gradCode.split('(')[1].split('deg')[0], 10),
          _0percPt, _100PercPt, 
          u = new EUtil(), 
          box = document.querySelector('.box'), 
          extremeOpts = [
            {'type': 'point', 'val': 0, '_0PercPt': { 'x': w/2, 'y': h }, '_100PercPt': { 'x': w/2, 'y': 0 }}, 
            {'type': 'interval', 'val': [0, 90], '_0PercPt': { 'x': 0, 'y': h }, '_100PercPt': { 'x': w, 'y': 0 }}, 
            {'type': 'point', 'val': 90, '_0PercPt': { 'x': 0, 'y': h/2 }, '_100PercPt': { 'x': w, 'y': h/2 }}, 
            {'type': 'interval', 'val': [90, 180], '_0PercPt': { 'x': 0, 'y': 0 }, '_100PercPt': { 'x': w, 'y': h }}, 
            {'type': 'point', 'val': 180, '_0PercPt': { 'x': w/2, 'y': 0 }, '_100PercPt': { 'x': w/2, 'y': h }}, 
            {'type': 'interval', 'val': [180, 270], '_0PercPt': { 'x': w, 'y': 0 }, '_100PercPt': { 'x': 0, 'y': h }}, 
            {'type': 'point', 'val': 270, '_0PercPt': { 'x': w, 'y': h/2 }, '_100PercPt': { 'x': 0, 'y':h/2 }}, 
            {'type': 'interval', 'val': [270, 360], '_0PercPt': { 'x': w, 'y': h }, '_100PercPt': { 'x': 0, 'y': 0 }}
          ];
      u.setStyle([[box, {'width': w+'px', 'height': h+'px', 'backgroundImage': gradCode}]]);
      angle = ((angle%360>=0)?(angle%360):(360+angle%360));
      for(var i = 0; i < extremeOpts.length; i++) {
        if((extremeOpts[i].type == 'point')?(angle == extremeOpts[i].val):(angle > extremeOpts[i].val[0] && angle > extremeOpts[i].val[0])) {
          _0PercPt = extremeOpts[i]._0PercPt;
          _100PercPt = extremeOpts[i]._100PercPt;
        }
      }
      return {'angle': angle, '_0PercPt': _0PercPt, '_100PercPt': _100PercPt};
    };
  };
  
  var pc = new PercCalculator(), 
      obj = pc.init(), 
      newg = document.querySelector('.newg'), 
      ok = document.querySelector('.apply'), 
      res = document.querySelector('.result'), 
      frm = document.querySelector('form');
  document.body.addEventListener('click', function(e) {
    if(!e.target.classList.contains('box')) return;
    res.innerHTML = Math.round(pc.computePerc(obj, e.clientX, e.clientY)*10000)/100 + '%';
    frm.classList.remove('revealme');
    res.classList.add('revealme');
  }, false);
  
  newg.addEventListener('click', function(){
    frm.classList.add('revealme');
    res.classList.remove('revealme');
  }, false);
  
  ok.addEventListener('click', function(e){
    var wEl = document.getElementById('w'), 
        hEl = document.getElementById('h'), 
        codEl = document.getElementById('cod'), 
        w = parseInt(wEl.value, 10), 
        h = parseInt(hEl.value, 10), 
        gc = codEl.value, 
        equiv = [['to top', '0deg'], ['to right', '90deg'], ['to bottom', '180deg'], ['to left', '270deg']];
    wEl.value = w;
    hEl.value = h;
    codEl.value = gc;
    if(gc.indexOf('deg') == -1) {
      if(gc.indexOf('to') == -1) gc = gc.split('(')[0] + '(180deg,' + gc.split('(')[1];
      else {
        for(var i = 0; i < equiv.length; i++){
          if(gc.indexOf(equiv[i][0]) != -1) {
            gc = gc.split('(')[0] + '(' + equiv[i][1] + gc.split(equiv[i][0])[1];
          }
        }
      }
    }
    frm.classList.remove('revealme');
    obj = pc.init(w, h, gc);
    e.preventDefault();
  }, false);
}());
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console