Absolutely true centred background image

后端 未结 2 1285
青春惊慌失措
青春惊慌失措 2021-01-28 03:57

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 05:02

    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.

提交回复
热议问题