skip to Main Content

In the snippet below, the horizontal scrollbar is appearing as expected. However I don’t understand why the vertical scrollbar appears as well.

Because the child and the parent have the same height, no vertical scrollbar should be necessary.

What I want is that the vertical scrollbar only appears when the child height exceeds the parents height

* {
  box-sizing: border-box;
}

#root {
  background-color: green;
  padding: 0;
  margin: 0;
  width: 600px;
  height: 400px;
  overflow-x: auto; /* Show horizontal scrollbar */
  overflow-y: auto; /* Show vertical scrollbar only if content overflows vertically */
}

#root2 {
  padding: 0;
  margin: 0;
  background-color: blue;
  width: 800px; /* Wider than parent to show horizontal scrollbar */
  height: 400px; /* Same height as parent initially */
}
<div id="root"><div id="root2"></div></div>

2

Answers


  1. 100% to take the size of the parent container instead.

    #root2 {
        padding: 0;
        margin: 0;
        background-color: blue;
        width: 800px; /* Wider than parent to show horizontal scrollbar */
        height: 100%; /* Same height as parent initially */
    }
    
    Login or Signup to reply.
  2. The problem is that the horizontal and vertical scroll bar breadth is 20px, approx.

    The scroll bars are adding extra height as well as width to the div.
    If you remove the horizontal scroll bar, it is fully okay in the code below:

    * {
      box-sizing: border-box;
    }
    
    #root {
      background-color: green;
      padding: 0;
      margin: 0;
      width: 600px;
      height: 400px;
      overflow-x: hidden; /* Show horizontal scrollbar */
      overflow-y: auto; /* Show vertical scrollbar only if content overflows vertically */
    }
    
    #root2 {
      padding: 0;
      margin: 0;
      background-color: blue;
      width: 800px; /* Wider than parent to show horizontal scrollbar */
      height: 400px; /* Same height as parent initially */
    }
    <div id="root"><div id="root2"></div></div>

    (CHECK IT IN FULL PAGE)

    The solution is to make the height auto in the parent container.

    OR

    add an extra height in the parent container.

    I don’t recommend the second option because the scroll bar height differs in other web browsers.

    I hope this helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search