保持图像始终居中,无论水平滚动

Keep an Image Always Centered Regardless of horizontal scroll

本文关键字:水平 滚动 图像      更新时间:2023-09-26

我试图创建一个图像的标题,但我需要它保持居中,无论水平滚动。让它保持居中并随着滚动条移动这样它就能一直显示了

我试着把它居中,并遵循我在SO中发现的一些例子,但它们都没有涵盖我需要的。

任何帮助都非常感谢

听起来你想要固定位置:

img.centered
{
  position: fixed;
  top: 50%;
  left: 50%;
  margin-left: -100px; /* Width of image /2 */
  margin-top: -100px; /* Height of image /2 */
}
HTML:

<body>
   <img class="centered" src="..." />
</body>

也许不是最好的方法,但它是有效的:

<div style="position:absolute; top:0px; width:100%; Height:100%; overflow:scroll;  left:0px;">ContenContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentt</div>
<div style="position:absolute; top:50%; left:50%;">Centerd stuff</div>

试一试:http://jsfiddle.net/chZWR/

尝试如下所述的背景修复技术:

更好的例子:http://davidwalsh.name/css-fixed-position-background-image

body    
{
    background:url(your-image.jpg) top right no-repeat;
    background-position:fixed;
}

下面是现场演示:

http://davidwalsh.name/demo/background-repeat.php


http://www.w3schools.com/cssref/pr_background-position.asp

例如:

body
{ 
    background-image:url('smiley.gif');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center; 
}

还有另一种方法:

工作示例

JS

var center = function () {
    var wh = $(window).height();
    ww = $(window).width();
    ch = $('#center').height();
    cw = $('#center').width();
    t = wh / 2 - ch / 2;
    l = ww / 2 - cw / 2;
    $('#center').offset({
        top: t,
        left: l
    });
};
$(document).ready(center);
$(window).resize(center);
CSS

#center {
    position:fixed;
}

使用这种方法有一个小优点,如果您需要更改图像的大小或将图像交换为另一个图像,则不需要调整定位。所有的计算都在脚本中为您完成了。