diff options
Diffstat (limited to 'files/zh-cn/web/guide/css/css_image_sprites/index.html')
| -rw-r--r-- | files/zh-cn/web/guide/css/css_image_sprites/index.html | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/files/zh-cn/web/guide/css/css_image_sprites/index.html b/files/zh-cn/web/guide/css/css_image_sprites/index.html new file mode 100644 index 0000000000..4a3e2bb7c9 --- /dev/null +++ b/files/zh-cn/web/guide/css/css_image_sprites/index.html @@ -0,0 +1,49 @@ +--- +title: 在 CSS 中实现图像合并 +slug: Web/Guide/CSS/CSS_Image_Sprites +tags: + - CSS + - CSS Image + - Graphics + - Guide + - Web +translation_of: Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS +--- +<div>{{cssRef}}</div> + +<p>CSS <strong>图像合并</strong>(<strong>Image sprites</strong>) 技术,亦作 CSS 贴图定位、图像精灵(sprite,意为精灵),被运用于众多使用大量小图标的网页应用之上。它可取图像的一部分来使用,使得使用一个图像文件替代多个小文件成为可能。相较于一个小图标一个图像文件,单独一张图片所需的 HTTP 请求更少,对内存和带宽更加友好。</p> + +<div class="note"> +<p>备注: 当使用 HTTP/2 时,使用多个小流量请求实际上可能更为带宽友好。</p> +</div> + +<h2 id="实现">实现</h2> + +<p>若要为所有类名为 <code>toolbtn</code> 的元素附加上一张图片:</p> + +<pre class="brush:css">.toolbtn { + background: url(myfile.png); + display: inline-block; + height: 20px; + width: 20px; +} +</pre> + +<p>为设置 <code>background-position</code> 以使每个按钮得到合并后图片中的正确部分,可以在 <code>background</code> 属性中的 {{cssxref("url()")}} 后添加 x, y 两个坐标值,或直接使用 {{cssxref("background-position")}} 属性。例如:</p> + +<pre class="brush:css">#btn1 {background-position: -20px 0px} +#btn2 {background-position: -40px 0px} +</pre> + +<p>这会将 ID 为 btn1 的元素的背景向左移 20px,ID 为 btn2 的元素的背景向左移40px(假设这两个元素都带有 <code>toolbtn</code> 这个类且应用了上面 <code>background</code> 属性中定义的图片背景)</p> + +<p>类似的,你也可以使用下面的代码添加悬停效果:</p> + +<pre class="brush:css">#btn:hover { + background-position: <var><pixels shifted right></var>px <var><pixels shifted down></var>px; +} +</pre> + +<h3 id="深入阅读">深入阅读</h3> + +<p>CSS Tricks 上的完整 Demo:<a href="http://css-tricks.com/snippets/css/perfect-css-sprite-sliding-doors-button/">http://css-tricks.com/snippets/css/perfect-css-sprite-sliding-doors-button/</a></p> |
