CSS:在x轴上固定位置但不在y轴上?

115

是否有一种方法可以仅在x轴上固定位置?这样,当用户向上滚动时,div标签将随之向上滚动,但不会横向滚动?


3
我可以为此问题提供JavaScript的解决方案吗? - Starx
1
你需要使用 JavaScript 来完成这个任务。 - LostLin
@Starx -- 这不仅可以,而且是必须的 :-) - Pete Wilson
我知道这是一个相当老的问题,但你还在为这个问题烦恼吗? - Starx
@Starx,如果你有纯CSS的解决方案,请告诉我,我还没有找到。 - kylex
显示剩余2条评论
17个回答

60

这也是一种使用脚本的简单技巧。您可以在这里检查演示。

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});
CSS
#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

更新 致谢:@PierredeLESPINAY

正如评论所述,为了使脚本支持css的更改而无需在脚本中重新编码它们。你可以使用以下方法。

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

演示 :)


@PeteWilson,好的,请检查这个解决方案。 - Starx
2
你认为在函数开始时获取 left 值,例如 init_left = $('#header').position()['left'] 或类似的方式,怎么样? - Pierre de LESPINAY
@PierredeLESPINAY,是的,非常好的观点。这将使其足够灵活,以支持更改。 - Starx
3
我喜欢这个解决方案,我刚刚自己使用了它。然而,我对它有一个问题,在平滑滚动(比如拖动滚动条)时,刷新有些卡顿。似乎JavaScript刷新比CSS刷新慢。有什么解决办法吗? - jsarma
@jsarma 是的,有一个解决方案:使用 requestAnimationFrame,然后您可以在每个帧上运行它而不会出现延迟,它将非常流畅(并且您可以使用变量来启用/禁用它)。$(window).scroll 事件存在一些延迟,并且不总是在每个帧上接收到(我认为),这会导致卡顿。 - Octo Poulos

18

1
我花了很长时间寻找解决方案,你的答案非常符合我的需求。 - Christopher Shaw
9
这对于垂直内容很好,但对于水平滚动无效。 - Cullub
26
这完全没有回答这个问题。 - Alohci

14
如果你的块最初是以静态方式定位的,你可以尝试这个方法。

$(window).on('scroll', function () {

  var $w = $(window);
  $('.position-fixed-x').css('left', $w.scrollLeft());
  $('.position-fixed-y').css('top', $w.scrollTop());

});
.container {
  width: 1000px;
}

.position-fixed-x {
  position: relative; 
}

.position-fixed-y {
  position: relative;
}

.blue-box {
  background:blue;
  width: 50px;
  height: 50px;
}

.red-box {
  background: red;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="position-fixed-y red-box">
  
</div>

The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do.

<div class="position-fixed-x blue-box">
  
</div>

DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA.

The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring.
  
 The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer.
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism).
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein.
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created.
</div>


9
现在移动设备已经占据了互联网市场的70%以上,您可以创建智能响应式内容。只需使用css即可轻松创建此功能,为一个容器使用overflow-x:scroll,为另一个容器使用overflow-y:scroll。您可以使用width: 100vw和height: 100vh轻松定位容器元素。单击示例进行测试,最适合移动设备,因为您看不到滚动条。

body{max-width:100%}
*{box-sizing:border-box;}
.container{background:#ddd;overflow-y:scroll;width:500px;max-height:100vh;}
.header{background: pink;}
.body{background: teal;padding:20px;min-width: 100%;overflow:scroll;overflow-y:hidden;min-height:300px;}
.body >div{min-width:800px;}
<body>
  <div class="container">
    <div class="header">
       Button 1 > Button 2 > Button 3
    </div>
    <div class="body">
      <div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
     </div>
    </div>
  </div>
</body>


我不喜欢底部滚动条只有在滚动到底部时才可见。 - Fanky
在移动浏览器上它不会出现。在Chrome中,您可以使用以下CSS隐藏它:.yourclass::-webkit-scrollbar-track, .yourclass::-webkit-scrollbar-thumb {display:none;}。在Firefox中,您可以通过将其放置在overflow:hidden容器之外来隐藏它。但这是另一个已经被回答过的问题,我相信这一点。 - EPurpl3

8

不,单纯使用CSS是不可能的。这种定位方式会将元素固定在视口中。我建议将元素简单地固定在视口的一侧(例如顶部、底部、左侧或右侧),以免干扰其他内容。


使用CSS完全可以实现,只是会失去侧向滚动条,在某些设备上甚至一开始就看不到它,请参见下面的答案。 - J Garcia

2

我在寻找一种简洁的方法来使我的头部/导航栏水平居中且能够响应大小变化时,无意中看到了这篇文章。

//CSS
.nav-container {
  height: 60px;  /*The static height*/
  width: 100%;  /*Makes it responsive to resizing the browser*/
  position: fixed;  /*So that it will always be in the center*/
}

//jQuery
$(window).scroll(() => {
  if ($(document).scrollTop() < 60) {
    $('.nav-container').css('top', $(document).scrollTop() * -1)
  }
})

当我们滚动页面时,该条栏会向上移出屏幕。如果您左右滚动页面,则它将保持固定。

谢谢兄弟,这个方案有效了。虽然很简单!!你真是个天才。 - Ram

2

Starx的解决方案对我非常有帮助。但是当我尝试使用它来实现一个垂直滚动的侧边栏时,遇到了一些问题。这是我最初的代码,基于Starx所写的:

function fix_vertical_scroll(id) {
    $(window).scroll(function(){
        $(id).css({
            'top': $(this).scrollTop() //Use it later
        });
    });
}

这与Starx的解决方案略有不同,因为我认为他的代码是设计为使菜单悬浮在水平方向而不是垂直方向。但这只是一个旁白。我对上述代码的问题在于,在许多浏览器中,或者取决于计算机的资源负载,菜单的移动会很卡顿,而最初的CSS解决方案则很流畅。我将这归因于浏览器在触发JavaScript事件时比实现CSS更慢。

我对这种卡顿问题的另一种解决方案是将框架设置为固定而不是绝对,然后使用Starx的方法取消水平移动。

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

#leftframe {
 position:fixed;
 width: 200;
}   

你可能会说我只是在用水平滚动的卡顿来换取垂直滚动的卡顿。但问题是,99%的滚动都是垂直的,当垂直滚动卡顿时比水平滚动卡顿更加恼人。
如果我还没有耗尽大家的耐心,这里是我关于这个问题的相关帖子:Fixing a menu in one direction in jquery

0

这是一个非常古老的帖子,但我已经找到了一个纯CSS解决方案,使用一些创造性的嵌套。我根本不喜欢jQuery方法...

这里有一个演示链接: https://jsfiddle.net/4jeuv5jq/

<div id="wrapper">
    <div id="fixeditem">
        Haha, I am a header. Nah.. Nah na na na
    </div>
    <div id="contentwrapper">
        <div id="content">
            Lorem ipsum.....
        </div>
    </div>
</div>

#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}

#fixeditem {
position: absolute;
}

#contentwrapper {
width: 100%;
overflow: scroll;
}

#content {
width: 1000px;
height: 2000px;
}

7
您的解决方案需要滚动内容容器 div 而不是实际窗口,这远非理想 - 您的演示表明了原因。您的内容超出页面右侧,但水平滚动条没有显示在屏幕上,这是一个很大的可用性问题。 - Niall

0

没错,你实际上可以只使用 CSS 来做到这一点...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

告诉我它是否有效


0
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

谢谢


这并没有提供问题的答案。如需对作者进行评论或请求澄清,请在他们的文章下方留言。 - ucMedia
1
请在您的答案中添加一些解释,以便其他人可以从中学习。 - Nico Haase

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接