I am trying to dynamically resize css grid layout boxes by dragging the column dividers (or resize placeholders) with the mouse.
I set resize: horizontal;
on the nav
element to resize, and it gets resized when I drag the small resize handle in the lower right corner of the element, but the width of the neighbouring column is not automatically adjusted which leads to overlap. Here is a broken codepen.
HTML:
<main>
<nav>#1</nav>
<header>#2</header>
<section>#3</section>
</main>
CSS:
main {
display: grid;
border: 3px dotted red;
grid-gap: 3px;
grid-template-columns: 200px 1fr;
grid-template-rows: 100px 1fr;
height: 100%;
}
nav {
grid-column: 1;
grid-row: 1;
grid-row: 1 / span 2;
resize: horizontal;
overflow: scroll;
border: 3px dotted blue;
}
I expected the css grid engine to automatically handle this case but apparently it does not.
I experimented with jquery-ui resizable but it does not seem to work well with css grids.
I am looking into how to do it with jquery by setting the grid attribute grid-template-columns/rows:
to a dynamic value but it is not clear how to catch the events thrown by resizing the element via the resize handle. The jquery resize event is only triggered on the window
object, and not on dom elements.
What might be a way to do it without having to handle low-level mouse events like dragstart/dragend?
The solution is to not use explicit fixed column size (
grid-template-columns: 200px 1fr;
) but use instead relative column sizes such asgrid-template-columns: 0.2fr 1fr;
— then the grid CSS engine will handle the resizing of adjacent boxes. Next thing is to add nested divs inside the grid boxes, set their min-height/width to 100% and make them resizable via jqueryui resizable.The fixed jsfiddle.
What you are looking to achieve is possible using only css. I've modified your example. The main takeaways are this: