Absolutely true centred background image

﹥>﹥吖頭↗ 提交于 2019-12-04 06:22:09

问题


oI have a site where a centred background image plays a vital part in a homepage animation.

The background centres great until the browser window cannot fit in the width of the site, at which point the background kind of left aligns.

This is my body code:

body {
line-height:1;
margin:0px auto;
padding:0px;
background:#90a830 url(img/bg.png) no-repeat center top;
}

The image popups shoot out from the correct place on the bg image. Try making the browser window smaller and you will see what i mean, the bg moves out of alignment.

thanks

Andy


回答1:


Set the background left to 50% and the background margin-left to be 0 minus the width of the background. That way it will always show the horizontal center of the image in the horizontal center of the browser window.

See my JSbin demo here. I reused your image so it looks weird with the other example images below!

CSS:

body {
  line-height:1;
padding:0px;
  margin-left:-575px; /* half your background image width */
  background:#90a830 url(http://www.apb-media.co.uk/uploads/background.jpg) 50% top;
}



回答2:


With the code you posted, the background image will always be centered on screen. On small screens, you want the houses to be center-screen; but this can only happen if the houses are in the center of the image. So my recommendation, if possible, would be to have the same amount of green grass on each side of the image, so that the houses are in the center of the image. Then you won't run into this problem.

If you can't change the image and the center of the houses is, say, 240px to the left of center of the image, you could center the houses on screen with something like this:

body {
    background: url(bg.png) calc(50% + 240px) 0 no-repeat;
}

Or perhaps you could just use that inside @media rules for smaller screens if you don't want the image to look off center on wider screens.



来源:https://stackoverflow.com/questions/21727191/absolutely-true-centred-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!