Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active April 23, 2018 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbogden/0189cd32659a224ad813 to your computer and use it in GitHub Desktop.
Save pbogden/0189cd32659a224ad813 to your computer and use it in GitHub Desktop.
responsive2

Side-by-side responsive graphics

The key is to use appropriate CSS for the containers...

  • display: inline-block; for side-by-side containers
  • vertical-align: top; so content aligns along the top (default is baseline of parent)
  • float: left; otherwise carriage-return between containers will take up space
  • width: 48%; must account for padding on left & right
<!doctype HTML>
<meta charset="utf-8">
<title>responsive2</title>
<style>
body {
margin: 0;
/* font-size: 0px; /* this hack has the same effect as 'float: left;' */
}
.container {
display: inline-block; /* for side-by-side containers */
vertical-align: top; /* so containers align along top; default is baseline of parent */
padding: 1% 1%; /* (top & bottom) (left & right) */
width: 48%; /* container will fit window (accommodates padding) */
float: left; /* accounts for carriage-return between containers */
background-color: #666;
font: 20px sans-serif;
}
#text-only {
background-color: steelblue;
}
#graphic {
background-color: #ccc;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<body>
<div class='container' id='graphic'></div> <!-- Note: carriage-return between containers can get rendered -->
<div class='container' id='text-only'>Don't forget to account for the padding.</div>
<script>
var n = 6, // "n" random circles determine the SVG's aspect ratio
radii = d3.range(n).map(function(){ return Math.random(); }),
x = radii.map(function(d, i) { return d + 2 * d3.sum( radii.slice(0, i) ); }),
width = 2 * d3.sum(radii),
height = 2 * d3.max(radii),
colors = d3.scale.category10();
var svg = d3.select("#graphic").append('svg')
.attr('viewBox', "0, 0, " + width + ", " + height) // min-x, min-y, width, height
.attr('preserveAspectRatio', "xMinYMid");
svg.selectAll('circle')
.data(radii)
.enter()
.append('circle')
.attr('r', function(d) { return d; })
.attr('cx', function(d,i) { return x[i]; })
.attr('cy', height / 2)
.style('fill', function(d,i) { return colors(i); });
setDivHeight();
d3.select(window).on('resize', setDivHeight);
function setDivHeight() {
var w = parseInt( d3.select("#graphic").style("width"), 10), // computed width
containerHeight = height * w / width;
d3.selectAll('.container').style('height', containerHeight + 'px');
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment