The SVG ViewBox

by Julien Etienne

HTML

<svg width='100%' height='50%' viewBox='0 0 8 4' >
    <rect x='0' y='0' width='2' height='2'/>
    <rect x='2' y='0' width='2' height='2'/>
    <rect x='4' y='0' width='2' height='2'/>
    <rect x='6' y='0' width='2' height='2'/>
    <rect x='0' y='2' width='2' height='2'/>
    <rect x='2' y='2' width='2' height='2'/>
    <rect x='4' y='2' width='2' height='2'/>
    <rect x='6' y='2' width='2' height='2'/>    
</svg>

CSS

html, body {
    background: #222;
    height: 100%;
    margin: 0;
    padding: 0;
}
svg {
    background: yellow;
}
svg rect:nth-child(1){
    fill: yellowgreen;
}
svg rect:nth-child(2){
    fill: crimson;
}
svg rect:nth-child(3){
    fill: orange;
}
svg rect:nth-child(4){
    fill: lightcoral;
}
svg rect:nth-child(5){
    fill: mediumblue;
}
svg rect:nth-child(6){
    fill: cyan;
}
svg rect:nth-child(7){
    fill: pink;
}
svg rect:nth-child(8){
    fill: turquoise;
}

JavaScript

// Resize the results window horizontally and verically to understand how the default viewBox preserves ratio.

// Now change the viewBox values to '0 0 80 40' understand how the units work. And resize again.