为了在我的页面上设置滚动条的样式,我曾经使用以下 CSS。它给了我完美的结果并将图像对齐在滚动条的中心。
background: #3395d2 url('img/thumb.png') no-repeat center;
border-radius: 8px;
border: 1px solid #004c98;
但是,我随后使用页面上的其他小图像获取了背景并创建了一个 sprite。然后再次为滚动条上的图像设置样式,我使用了以下 CSS。然而,这次它没有居中对齐。
background: #3395d2 url('img/small-images.png') no-repeat center;
border-radius: 8px;
border: 1px solid #004c98;
background-position: 0 -702px;
我如何编辑我的代码,使图像仍然在滚动条的中间对齐,尽管在 Sprite 中?
最佳答案
首先,一旦您重新定义了 background-position
,center
就不再重要了。
background: #3395D2 url('http://s21.postimg.org/3ymz2gr8n/small_images.png') no-repeat center;
等同于说:
background-color: #3395D2;
background-image: url('http://s21.postimg.org/3ymz2gr8n/small_images.png');
background-repeat: no-repeat;
background-position: center;
所以当你说
background-position: 0 -702px;
说完
background-position: center;
你正在覆盖它。
就是说,您还有另一个问题。仅仅因为它是一个 sprite 并不意味着 CSS 将您的 sprite 中的每个图像都视为单独的图像。如果你垂直对齐它,你会在你的 Sprite 中看到其他图像。我建议将 sprite 设置为水平而不是垂直,然后调整 background-position-x
(当前代码中的 0
)以在您的 sprite 中选择您想要的图像和 background-position-y
(当前代码中的 -702px
)使其在滚动条上垂直居中。
关于html - 如何在使用背景位置 css 时移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892208/