How to make a div vertically scrollable without content using CSS ?
Last Updated :
15 May, 2023
In this article, we will see how we can create a vertical scrollable section using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style,
HTML Code:
- Create an HTML div element with the class container.
- Created three more nested div with class box
- Write some content inside each div with the class box.
CSS Code:
- The “scroll” option is added in this case to always show the scrollbar for the overflow-y property.
- The height is set to 100vh for 100% height of the viewport, which is set for the reason that if the contents exceed, it adds a scrollbar.
- The scroll-snap-type is set to y so that the direction of scroll-snapping is in the y-axis for the container div. This property is added if the browser is needed to be stopped at a particular time. This forces scrolling to a snap point on the y-axis.
- The scroll-snap-align property is used on elements with the class “box” to set the position that scrolling will snap to. The scroll-snap-align is used to tell the point where the scrolling should stop.
Example: In this example, we create a vertical scrollable using the above approach.
HTML
<!DOCTYPE html>
< html >
< head >
< style type = "text/css" >
body {
margin: 0;
}
/* Adding scroll snap type mandatory
and scroll direction to y axis*/
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
/* 100% height of the viewport */
height: 100vh;
}
/* Adding general css to box and
aligning snap to start */
.box {
height: 100vh;
color: #fff;
text-align: center;
line-height: 100vh;
font-size: 5rem;
scroll-snap-align: start;
}
/* Setting different colors to all boxes */
.box:nth-child(1) {
background: #5e38ff;
}
.box:nth-child(2) {
background: #fe802b;
}
.box:nth-child(3) {
background: #00bf71;
}
</ style >
</ head >
< body >
< div class = "container" >
< div class = "box" ></ div >
< div class = "box" ></ div >
< div class = "box" ></ div >
</ div >
</ body >
</ html >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...