如何向 div 添加滚动条?

我有一个弹出窗口,显示一些结果,我希望一个滚动条显示,因为结果被切断(我不希望弹出窗口太长)。

237041 次浏览

You need to add style="overflow-y:scroll;" to the div tag. (This will force a scrollbar on the vertical).

If you only want a scrollbar when needed, just do overflow-y:auto;

<div class="scrollingDiv">foo</div>


div.scrollingDiv
{
overflow:scroll;
}

Css class to have a nice Div with scroll

.DivToScroll{
background-color: #F5F5F5;
border: 1px solid #DDDDDD;
border-radius: 4px 0 4px 0;
color: #3B3C3E;
font-size: 12px;
font-weight: bold;
left: -1px;
padding: 10px 7px 5px;
}


.DivWithScroll{
height:120px;
overflow:scroll;
overflow-x:hidden;
}

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}




</style>
</head>


<body>






<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>




</body>
</html>

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
overflow-y: auto;
max-height: 100px;
}

If you have a CSS file, you can define a call for the <div> element and assign the overflow: auto CSS property.

In the HTML file: <div class="container">

In the CSS file you put:

.container{
overflow: "auto";
}

There are multiple ways to achieve a scroller on a div, here find a simple easy way one with an easy explanation.

.my_scroll_div {
overflow-y: auto;
max-height: 100px;
}

Here is a bit explanation of the above code.

overflow-y: auto;

The overflow-y property of CSS adds a scroller when needed, If we want to add the scroller after a specific height (e.g 100px in our case) Then,

max-height: 100px;

We add the max-height property of CSS so for example to add a scroller after 100px of height then max-height: 100px; is used.

I hope this explanation is helpful in clearing the concepts as well.