html - 如何在使用背景位置 css 时移动图像

标签 html css background background-position

为了在我的页面上设置滚动条的样式,我曾经使用以下 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 中?

JSFiddle

最佳答案

首先,一旦您重新定义了 background-positioncenter 就不再重要了。

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/

相关文章:

jquery - jQuery 的 val() 和 prop() 方法是否使用 html 转义值?

javascript - 模态 Bootstrap 4 不显示

html - 我可以向纯 css slider 添加点吗?

javascript - 如何使用 jQuery 禁用文本区域 + 提交按钮?

iphone - 如何每小时在后台运行约 30 秒的进程(iphone 应用程序)

html - CSS - 内部 div 不会留在外部 div 容器内

c# - 从 html 单选按钮获取值 - 在 aspx-c#

html - Bootstrap 垂直对齐列内容与移动优化

html - 背景 slider

html - 如何将背景图像作为 block 重复