Home > Back-end >  Adjust the width of two side-by-side divs by user drag operations
Adjust the width of two side-by-side divs by user drag operations

Time:12-13

I have 2 side-by-side div. If there is any simple solution that allows user to adjust the width of two div by dragging.

If the width of one div increase, the the width of another div decreases, and keep the sum of 2 div width the same.

It would be great if it can be implemented by pure javascript or css. And addding any other items, like div, is welcomed.

The code of 2 divs is as following:

.left {
    float: left;
    width: 49%;
    min-height: 50px;
    border: 2px dashed #f0f
}

.right {
    float: right;
    width: 49%;
    min-height: 50px;
    border: 2px dashed #00f
}
<div ></div> 
<div ></div>

Appreciate any ideas!

CodePudding user response:

use the textbox approach ? since the textbox is resizable you can style your textbox like a div

take a look at this post for inspiration: Table with sticky header and resizable columns without using JQuery

CodePudding user response:

Out of curiosity I created a small trial and found out that it was easier accomplished using a main flexbox container .wrapper containing the .left and .right elements and have the flexbox mechanism do the hard work.

Two things:

  • When using resize, property overflow needs to be auto to make the handle visible (tested on Windows Firefox and Chrome/Edge).
  • Choose one of child elements that can be resized and hold the handle, I chose .left. Because they are flexbox child elements, using flex: 1 on the other element (.right) the flexbox mechanism will make that element follow the size of the resized element and fill any remaining space.

MDN Reference: resize

/* Flexbox container for easy resizing of .right */
.wrapper { display: flex }

.left, .right {
    /* initial size, browser will remember last state until page reload */
    width: 50%;
    min-height: 50px; /* at least some meat to show */
    min-width : 50px;
}

.left {
    overflow: auto; /* required to make the handle visible */
    resize: both;   /* enable resize in either direction   */
           /* use horizontal/vertical for single direction */
}

.right {
    flex: 1; /* will fill the remaining horizontal/vertical space */
}

/* Eye-candy */
.left  { border: 2px dashed #f0f }
.right { border: 2px dashed #00f }
<div >
    <div  ></div>
    <div ></div>
</div>

  • Related