如何具有可垂直滚动和水平固定的固定侧边栏

时间:2019-11-28 22:49:45

标签: html css bootstrap-4

我的侧边栏中的内容可能需要向下滚动才能阅读。我尝试在线搜索,但找不到适合我的入门资源。您的帮助将不胜感激。

更新

对不起,我没有正确询问。我的意思是补充说,侧栏在垂直滚动时应以与主页滚动相同的速度移动。

2 个答案:

答案 0 :(得分:1)

我创建了一个示例来帮助您。

.content-section {
  min-height: 2000px;
}
.sidebar-section {
  position: absolute;
  height: 100%;
  width: 100%;
}


.sidebar-item {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	
	/* Position the items */
	// &:nth-child(2) { top: 25%; }
	// &:nth-child(3) { top: 50%; }
	// &:nth-child(4) { top: 75%; }
}


.make-me-sticky {
  position: -webkit-sticky;
	position: sticky;
	top: 0;
  max-height:400px;
  overflow-y:scroll;
  
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<html>
<head>
 <title>Test</title>
</head>
<body>

  <div class="container-fluid">

 <div class="row">
             <div class="col-5">

              <div class="sidebar-item">
                <div class="make-me-sticky">
                        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
                </div>
              </div>
         
            </div>
            <div class="col-7">

                <div class="content-section">
                    <h2>Content Section</h2>
                </div>
            </div>

</div>
</div>
</body>

</html>

答案 1 :(得分:0)

尝试使用<meta name="viewport" content="width=device-width, initial-scale=1"> 查看CSS position: sticky,其中10px是粘性容器与屏幕顶部的距离。

请注意,如果您遇到问题,则IE11确实存在一些向后兼容性问题。

https://www.w3schools.com/howto/howto_css_sticky_element.asp#:~:targetText=An%20element%20with%20position%3A%20sticky,(like%20position%3Afixed)