2

我正在尝试使用图像创建标题,但无论水平滚动如何,我都需要它保持居中。所以几乎保持它居中并随着滚动移动,所以它总是显示。

我尝试将其居中并遵循我在 SO 中找到的一些示例,但它们都没有涵盖我需要的内容。

任何帮助是极大的赞赏

4

4 回答 4

6

听起来你想要固定位置:

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>
于 2013-05-28T15:38:47.723 回答
1

还有另一种方法:

工作示例

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;
}

使用此方法有一个小优势,如果您需要更改图像的大小或将图像换成另一个,则无需调整位置。所有计算都在脚本中为您完成。

于 2013-05-28T16:10:40.317 回答
1

尝试这里描述的背景修复技术:

更好的例子:

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; 
}
于 2013-05-28T15:37:34.477 回答
1

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

<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/

于 2013-05-28T15:42:05.947 回答