Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

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.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Pyramid Chart Component</h1>
<div id='example'></div>

<div class='description'>
  <h2>Plain</h2>
  <p>It's plain HTML and CSS in output.</p>
  <h2>Responsivness</h2>
  <p>It's responsive by default. Just set the height and width for your container.</p>
  <h2>Interactivity</h2>
    <p>You can use both JS or CSS to make it interactive. In this example only <code>:hover</code> is used</p>
</div>
<div class='description'>
  <h2>Defaults</h2>
  <p>The default styles are inline inside the component.</p>
    <p>The default <strong>slices</strong> styles are <strong><code>clip-path</code></strong>, <strong><code>height</code></strong>, <strong><code>width</code></strong>. <br />
  Them <strong>should not be overrided</strong>.</p>
  <p>The default <strong>container</strong> styles make it a flexbox. You could override it, but it's not recommended.</p> 
  <h2>Use in your Pens</h2>
  <p>You can use this Pen's JS as a dependency in your Pens.</p>
  <p>This example is tuned inside HTML section, so don't worry — it will not be drawn in your code.</p>
</div>
<div class='description'>
  <h2>Known issues</h2>
  <ol>
    <li>
      <p>
      <strong>Slice height percentage</strong>: you can't tweak it.
      A slice height is a percentage relative to the total container height.
      <br />
      You can tweak the width, as it's 100% of the total;
      </p>
      <p>
      <strong>Workaround</strong>: use paddings to resize;
      </p>
      <p>
      <strong>Fix</strong>: you can try to put slices inside containers and apply the calculated height to containers while the slices will be 100% in height.
      </p>
    </li>
    <li>
      <p>
        <strong>Borders</strong>: that's it — you can't just assign plain css borders to it.
      </p>
      <p>
      <strong>Workaround</strong>: currently no simple workarounds.
      </p>
      <p>
      <strong>Fix</strong>: as in previous issue you can try to play with containers. <br />
        You can use container background and apply to it the same <code>clip-path</code>. If container will be  bigger than slice, it will look like a border.
      <p>
        Another option could be using SVG.
      </p>
      <p>
        The drawback is that it kills the HTML & CSS simplicity of this component.
      </p>
    </li>
  </ol>
</div>
<script>
  // I use the JS source as external for other pens, that's why I render this example inline here
window.onload = function () {
  ReactDOM.render(
    React.createElement(
      Pyramid,
      { data: [
          { value: 1, 
            props: { 
              title: '25 percent', 
              style: { backgroundColor: 'steelblue' }
            }},
          { value: 1, 
            props: { 
              title: '25 percent', 
              style: { backgroundColor: 'yellow' }
            }},
          { value: 1, 
            props: { 
              title: '25 percent', 
              style: { backgroundColor: 'khaki' }
            }},
          { value: 1, 
            props: { 
              title: '25 percent', 
              style: { backgroundColor: '#C86428' }
            }}
      ]}),
    document.getElementById('example')
  )
}
</script>
              
            
!

CSS

              
                h2 {
  margin: .7em 0 .3em;
}
h2+p {
  margin-top: 0;
}

.description {
  vertical-align:top;
  display: inline-block;
  max-width: 400px;
}

#example {
  vertical-align:top;
  display: inline-block;
  width: 300px;
  height: 300px;
  padding: 0 50px;
  margin: auto;
}

body {
    background: llinear-gradient(to top, #ece9e6, #ffffff);

}

/* 
* This CSS can be safely changed.
* All important CSS rules are inline inside the component
*/

.pyramid-chart-container {
  padding: 10px;
  
  .pyramid-chart-slice {
    margin: 1px 0;
    transition: all .5s ease;
    
    &:nth-child(odd) {
      background: blue;
    }
    
    &:hover {
      margin-left: 20%;
    }
  }
}
              
            
!

JS

              
                const trapezoidPath = (height, topBase, bottomBase) => {
  const
    topBaseOffset = (100 - topBase) / 2,
    bottomBaseOffset = (100 - bottomBase) / 2
  
  const
    topRule = topBaseOffset === 0 ? '50% 0' : `${topBaseOffset}% 0%, ${100 - topBaseOffset}% 0%`,
    bottomRule = `${100 - bottomBaseOffset}% 100%, ${bottomBaseOffset}% 100%`
  
  return `polygon(${topRule}, ${bottomRule})`
}

class Pyramid extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      styles: this.calculateStyles(this.props.data)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps !== this.props) {
      this.setState({ styles: this.calculateStyles(nextProps.data) })
    }  
  }

  calculateStyles(data) {
    const totalArea = data.reduce((acc, entry) => acc + entry.value, 0)

    // At each iteration of data, we calculate a triangle sizes; this triangle is
    // the sum of the slices that we already iterated from top to bottom of our "pyramid"
    //
    // ````/\ 
    // ```/..\ - first slice --> triangle
    // ``/....\- second slice + first --> triangle
    // `/______\ - third slice + first + second --> triangle
    // 
    // To find the sizes of each individual slice, we will just substract
    // the current triangle size from the previous value
    let
      areaAcc = 0,
      prevSizesCoef = 0
    
    // Create the style data for each item
    const styles = data.map(item => {
      // Calculate the area ratio of current triangle
      areaAcc = areaAcc + item.value
      const areaRatio = areaAcc / totalArea
      
      // Calculate the slice sizes coefficient
      const sizesCoef = Math.sqrt(areaRatio)
      const sliceHeight = sizesCoef - prevSizesCoef
      
      // Calculate path style
      const path = trapezoidPath(sliceHeight * 100, prevSizesCoef * 100, sizesCoef * 100)
      
      // Update
      prevSizesCoef = sizesCoef
      
      return {
        clipPath: path,
        height: sliceHeight*100 + '%',
        width: '100%'
      } 
    })

    return styles
  }

  render() {
    const
      { data, containerProps } = this.props,
      { styles } = this.state
    
    const containerStyle = {
      height: '100%',
      width: '100%',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      boxSizing: 'border-box'
    }
    
    return (
      <div {...containerProps}
        style={{ ...containerProps.style, ...containerStyle }}
        className={`pyramid-chart-container ${containerProps.className || ''}`}
        >
        {data.map((item, index) => 
          <div {...item.props}
               style={{ ...(item.props && item.props.style), ...styles[index] }}
               className={`pyramid-chart-slice ${item.props && item.props.className || ''}`}>
          </div>
          )}
      </div>
    );
  }
}

Pyramid.defaultProps = {
  data: [],
  containerProps: {}
}
              
            
!
999px

Console