-1

I have a Bootstrap 5 website page with two vertically stacked <div>s, one below the other.

The page I'm designing would be useless if the bottom <div> was not visible, or if either <div> were too small.

Questions:

  1. Is there any way to dynamically set the height of these <div>s when the page loads so that the border between them is roughly in the center of the display on all systems? It can be based on CSS or JavaScript.
  2. Is there a way to allow the user to adjust the border between the two <div>s by moving it vertically in a way that adjusts the height of the two <div>s?

Working CodePen: https://codepen.io/softcircuits/pen/mdGomeP

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

1 Answers1

1

Here is a simple solution using pure CSS.

<div class="myDiv" id="div1"></div>
<div class="myDiv" id="div2"></div>
html, body {
    margin: 0;
}

.myDiv {
    border: 2px solid black;
    height: 50vh;
    box-sizing: border-box;
    /* min-height: 200px; */
    resize: vertical;
    overflow: auto;
}

#div1 {
    background-color: cornflowerblue;
}

#div2 {
    background-color: crimson;
}

Question 1:

For the border between them to be centered, you can set the height of each to half the viewport using the vh unit. vh is a relative CSS unit defined such as 100 vh equals the browser's view port's height.

However setting height: 50vh sets the height of the div's content to 50vh instead of the entire div, therefore the height would be 50vh + padding if any + border thickness, and to avoid that use box-sizing: border-box. This makes the entire height including any padding and the border thickness 50vh.

More on box-sizing property: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

You can also add min-height if you want to avoid the divs being to small.

Question 2:

To add the ability for a user to resize a div add the following:

resize: vertical;
overflow: auto;

More on resize property: https://developer.mozilla.org/en-US/docs/Web/CSS/resize

I'm not sure if that's what you are looking for regarding question 2.

  • Thanks. This seems to solve the issue of placing the border at the center of the display nicely. Will take me some time to play around with it. For me second question, I think I need some sort of UI component like jQuery-UI. But I will play with your stuff for this as well. – Jonathan Wood Mar 27 '23 at 20:21
  • 1
    Of course! Take a look at the following article and StackOverflow question, they might what you are looking for. https://medium.com/the-z/making-a-resizable-div-in-js-is-not-easy-as-you-think-bda19a1bc53d https://stackoverflow.com/questions/59793365/how-to-make-resizable-div-resizable-from-sides – Michael Knightly Mar 27 '23 at 20:27