简体   繁体   English

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

[英]Keep an Image Always Centered Regardless of horizontal scroll

I'm trying to create a title with an image, but I need it to stay centered regardless of the horizontal scroll. 我正在尝试使用图像创建标题,但是无论水平滚动如何,都需要使其保持居中。 So pretty much keep it centered and move with the scroll so it's always showing. 因此,几乎可以保持它居中并随滚动一起移动,从而始终显示它。

I tried centering it and following a few examples I found in SO but none of them covers what I need. 我尝试将其居中,并遵循在SO中找到的一些示例,但这些示例都没有涵盖我所需要的。

Any help is greatly appreciated 任何帮助是极大的赞赏

It sounds like you want fixed position: 听起来您想要固定位置:

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

HTML: HTML:

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

Try the background fixing technique as described here: 请尝试按以下说明使用背景修复技术:

Better example: 更好的例子:

http://davidwalsh.name/css-fixed-position-background-image http://davidwalsh.name/css-fixed-position-background-image

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

Here is the live demo: 这是现场演示:

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


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

for example: 例如:

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

maybe not the best way but it works: 也许不是最好的方法,但是它可行:

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

Try it: http://jsfiddle.net/chZWR/ 试试看: http : //jsfiddle.net/chZWR/

Yet another way to do this: 还有另一种方法:

Working Example 工作实例

JS 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 的CSS

#center {
    position:fixed;
}

There is a small advantage to using this method, if you should need to change the size of the image or swap the image out for another, you won't need to adjust the positioning. 使用此方法有一个小的优势,如果您需要更改图像的大小或将图像换成另一张,则无需调整位置。 All the calculations are done for you in the script. 在脚本中为您完成了所有计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM