Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Add Scrollbars to a Block (e.g. A <div> Element)

If you need to customize a list box then the <select> HTML element might not be enough. In such a case you’d like to have something that simulates the <select> behaviour.

Here is the code to use to obtain a custom list box:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
  <head>
  </head>

  <body>
    <div style="width: 200px; height: 200px; overflow: auto;">
      <table width="100%" height="100%">
        <script>
          for (var i = 0; i < 30; i++) {
            if (i % 2 == 0) {
              document.write(
              "<tr style='background-color:#0066ff; color: #ffffff'>" +
              "<td>JavaScript</td></tr>");
            }
            else {
              document.write(
              "<tr style='background-color:#ff6600; color: #ffffff'>" +
              "<td>JavaScript</td></tr>");
            }
          }
        </script>
      </table>
    </div>
  </body>
</html>

The key CSS element is overflow. If you use overflow: auto then the scrollbars are displayed only if they are needed. If you want to display them in any case then you need to use overflow: scroll.

Comments