首页 > 解决方案 > 如何使 div 跟随/固定水平滚动,但不垂直?

问题描述

如何使 div 仅通过水平滚动而不是垂直保持固定?

正如你所看到的,当我从左到右滚动时,顶部导航栏应该是固定的。

在此处输入图像描述

尽管当我向下滚动时,顶部导航栏也随之而来,但与预期不同。当用户向下滚动时,它应该保持在顶部。

在此处输入图像描述

这是我的 CSS 来实现这一点,只需使用position: fixed;width: 100%;

/* Nav */
.nav {

  height: 60px;
  position: fixed;
  top: 0;

  width: 100%;
}

我不知道我是否需要使用 JavaScript 来实现这一点。

谢谢

  <!-- Nav -->
  <div class="nav">

    <!-- Logo -->
    <img class="logo" src="images/logo.png" alt="">

    <!-- Logout button -->
    <button class="logout-btn" id="logout_user">Logout</button>

    <!-- User's email -->
    <span id="users_email"></span>

  </div>
/* Logo */
.logo {
  max-width: 100%;
  max-height: 100%;

  margin-left: 50px;
}
/* Logout Button */
.logout-btn {
  float: right;
  position: relative;
  top: 40%;

  margin-right: 30px;

  border: none;
  color: white;

  padding: 5px 7px 5px 7px;
  text-align: center;
  text-decoration: none;

  font-size: 100%;
  border-radius: 10px;

  background-color: lightcoral;
}
/* User's email */
#users_email {
  float: right;
  position: relative;
  top: 45%;

  margin-right: 15px;

  font-size: 100%;
}

唐老鸭解决方案(两者)导致以下结果。虽然导航栏在垂直滚动时不会跟随,但它不会在屏幕上伸展,并且里面有一个滚动条。

在此处输入图像描述

标签: javascripthtmlcss

解决方案


 body{
margin:0px;
padding:10%;
background:#000;
}
.wrapper{
margin:0px auto;
width:50%;
background:#ccc;
border:2px solid #fff;
}
.box{
width:100%;
height:250px;
overflow-x: auto;
  overflow-y: none;
}
.box p{
font-size:15px;
fon-weight:normal;
color:#333;
padding:2%;
line-height:25px;
}
<div class="wrapper">
<div class="box">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
</div>


推荐阅读