Right aligned CSS sprites

Right aligned CSS sprites

Posted on 03/09/2009 by CharlieLaw

The benefits of CSS sprites are well document.

  • Improved web site perfomance due to a reduced in http requests
  • Simple rollovers without JavaScript
  • Easy management of multiple images within one file.

Due to these benefits I find myself keen to use CSS sprites whenever I can. However, until recently there has been one situation where I found myself unable to add particular images to CSS sprites. Right aligned images.

When positioning a background image you set the top and left positions like so:

background-position:10px 30px

The first value represents the horizontal position and the second represents the vertical position. This example would move a background image 10px from the left and 30px from the top. You can use other units like relative numbers (%, em), or the length keyword combinations top, bottom, left, center, right.

Positioning images within a CSS Sprite you use the units (pixels or percentage) with a negative value

background-position: -10px -30px

I like to think of this as clipping an image, you are basically saying cut 10px from the left of my image and 30px from the top and show the rest of the image from that point in the the top left position. As you are using the positioning coordinates to “clip” the image you are unable to move the image position like you can with positive values. Here’s an example page of left aligned sprites.

This works for left aligned images however if you want the image to be right aligned things are a bit different. Although the W3C state you can’t do this, it is possible to combine units with lengths. You can use the keyword or percentage to get the right hand side of the image and pixels to get the top coordinate. e.g.

background-position: 100% -10px
or

background-position: right -10px

I have x-browser tested this technique in IE 5.5 upwards, FF 2 & 3, Opera and Safari on Mac and Windows and it works fine and the CSS still validates too. You can see the right aligned sprites on this demo page.

When the sprite contains multiple images positioned horizontally then the images to the left may get shown. What I tend to do is set up a seperate sprite for all images that are right aligned, though if you want to keep everything in one place you could just place all sprites vertically or make the sprite extra large and right align the appropriate images within the sprite with plenty of white space to the left.

转载于:https://www.cnblogs.com/johngeng/archive/2010/11/03/1867721.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值