Resize Flex

Resizing FlexBox Elements

by PhilM

HTML

<body class="vbox">
</body>

CSS

html, body {
  width: 100%;
  height: 100%;
  font-family: Tahoma;
  font-size: 14px;
  margin: 0px;
  padding: 0px;
  background-color: rgb(220, 230, 255);
}

.hbox {
  display: flex;
  flex-direction: row;
}

.vbox {
  display: flex;
  flex-direction: column;
}

.flexParent{
  display: flex;
  justify-content: center;
  align-items: center;
}

.segment {
  background-color: white;
  margin: 8px;
  border: 1px dotted rgb(180, 79, 40);
  border-radius: 10px;
  position: relative;
}

.sizeDisplay{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  border-radius: 10px;
  font-size: 24px;
  color: white;
  font-weight: bold;
}

.sizingDisplay{
  background-color: rgba(50,50,0,0.5);
  border: 2px solid yellow;
}

span {
  background-color: rgb(230,230,230);
  padding:8px;
  border: 1px solid slateblue;
  border-radius: 5px;
  cursor:default;
}

JavaScript

var data = [10, 10, 10];
var currentSizer;
var startPoint;
var startSize;
var currentSize;

var segments = d3.select("body").selectAll(".segment")
    .data(data);

var sizeDisplays = d3.select("sizeDisplay");

segments.enter().append("div").classed(
    {"segment": true, "flexParent": true});

segments.append("span").text("Size Me")
    .on("mousedown", startSizingMe);

function updateSegmentSize(){
  segments.style("flex", getSize);
  sizeDisplays.text(getParentSize);
}

function getSize(d, i){
  //console.log(d);  
  return d;
}

function getParentSize(d, i){
  //console.log(data[i]);  
  return d3.select(this.parentNode).datum();
}

function startSizingMe(){
  d3.event.stopPropagation();
  d3.event.preventDefault();
  startPoint = d3.mouse(document.body);
  var thisNode = this;
  currentSizer = d3.select(this.parentNode);
  startSize = currentSizer.datum();
  d3.select("body").on("mouseup", stopSizingMe)
    .on("mousemove", sizeMe);
  
  // show sizing indicators
  sizeDisplays = segments.append("div")
    .attr("class", "sizeDisplay flexParent");
  
  currentSizer.select(".sizeDisplay").classed("sizingDisplay", true);
  
  updateSegmentSize();
}

function stopSizingMe(){
  d3.select("body").on("mousemove", null)
    .on("mouseup", null);
  sizeDisplays.remove();
  currentSizer = null;
}

function dSize(){
  return Math.max(1,startSize + Math.floor(
    (startPoint[1] - d3.mouse(document.body)[1])/8));
}

function sizeMe(){
  var newSize = dSize();
  currentSizer.datum(newSize);
  updateSegmentSize();
}

updateSegmentSize();