(译)css伪元素技巧

CSS background image hacks

Emulating background image crop, background image opacity, background transforms, and improved background positioning. A few hacks relying on CSS pseudo-elements to emulate features unavailable or not yet widely supported by modern browsers.

依靠css伪元素,我们可以模拟一些目前现代浏览器未实现或者是没有被广泛支持的一些属性,如背景裁切,背景透明度,背景变换,复杂背景定位。

Demos: Example CSS background image hacks

Pseudo-element hacks can fill some gaps in existing browser support for CSS features, without resorting to presentational HTML. In some cases, they even make it possible to emulate things that are not currently part of any W3C working draft, like background transforms and background image opacity.

伪元素技巧不需要任何额外的html标签就可以填补浏览器对一些css特性支持的空白,甚至可以模拟一些尚未进入W3C草案的css特性,如背景变换及背景透明度

Most of the hacks in this article tie in with the pseudo-element hack described in an earlier article – Multiple Backgrounds and Borders with CSS 2.1. That article already describes how to emulate multiple background support and its demo page shows several other uses of the basic principle. This article presents a few of those effects and applications in greater detail.

本文利用伪元素的大部分技巧均在早前的文章Multiple Backgrounds and Borders with CSS 2.1描述过,那篇文章已经讲解了怎样利用伪元素模拟css多背景特性,文章的demo页也展现了一些利用伪元素来实现其他特性的基本原理。

这篇文章将会详细讲解其中的几个效果与应用

Emulating background-crop

Known support: Firefox 3.5+, Opera 10+, Safari 4+, Chrome 4+, IE 8+

Demo: Pseudo background-crop

模拟背景剪裁

Background image cropping can be emulated in modern browsers using only CSS 2.1. The principle behind a pseudo background-crop is to apply a background-image to a pseudo-element rather than the element itself. One example would be to crop an image to display in the background. Another would be to crop an image sprite to display icons alongside text in links.

利用css2.1即可模拟背景裁切效果。原理是把背景图片作为伪元素的背景,而不是作为原本容器的背景。下面第一个例子的效果是裁剪一部分背景,第二个效果可以裁剪css sprite,利用这个特性来制作文字旁边的小图片

In several cases, using pseudo-elements may have advantages over existing, alternative techniques because it combines their strengths and avoids some of their weaknesses.

某种程度上,相比其他可用的方法,使用伪元素是有优势的,伪元素结合了一些方法的优点,而某种程度上又可以规避他们的缺点

Google, Facebook, and Twitter all make use of empty DOM elements to crop dense sprites and display icons next to certain links in their interfaces. The alternative is not to use empty elements but be forced into using multiple images and/or to design sub-optimal image sprites that have their component images spaced out.

Google facebook  twitter 均使用空白dom元素来裁切他们复杂的精灵图,用来实现界面上链接旁的图标效果。

Pseudo-elements can be used in much the same way as empty DOM elements. This simultaneously eliminates the need for presentational HTML and doesn’t depend so heavily on an image sprite’s design. Using pseudo-elements for this purpose does have its own drawback – a lack of support in legacy browsers like IE6 and IE7. However, the technique will progressively enhance capable browsers while leaving a perfectly usable experience for incapable browsers.

伪元素也可以用类似空白dom元素应用的方式来使用。同时,使用伪元素不需要依赖额外的html标签,而且不会过分依靠精灵图。此方法的缺点是ie6,7浏览器不支持。利用此种方式,可以实现渐进增强,加强支持此特性浏览器页面的表现效果,而低版本浏览器仍采用空白元素的办法,同样可以完美的得到我们想要的效果。

Example code: cropping a sprite

This example shows how to crop icons that are part of a dense image sprite that uses a 16px × 16px grid. It uses a simple list and specifies a class for each type of action.

这个例子展示了如何从一张排列紧密的雪碧图中裁切出你需要的图标。裁切尺寸为16*16。只需要创建一个ul列表,在需要生效的部分指定一个class即可

<ul>

   <li><a href=”#”>Save</a></li>

   <li><a href=”#”>Delete</a></li>

   <li><a href=”#”>Share</a></li>

   <li><a href=”#”>Comment</a></li>

</ul>

Styling can be applied to present this list in whatever way is needed. From that base, a pseudo-element can be created and then treated as you would an empty, inline DOM element (e.g. <span>).

应用样式可以以各种方式展示这个列表,在此基础上我们利用伪元素,这里你完全可以把伪元素当作空白标签来使用 比如span

In this case, the :before pseudo-element is used and sized to match the sprite’s grid unit. It could be sized to whatever dimensions are required to match a section of the sprite that needs to be cropped.

:Before伪元素的尺寸正好可以匹配精灵图的一个网格(即16*16)。同样你可以根据所裁切的部分,随意设置伪元素的尺寸

.actions a:before {

   content:””;

   float:left;

   width:16px;

   height:16px;

   margin:0 5px 0 0;

   background:url(sprite.png);

}

.save a:before {background-position:0 -16px;}

.delete a:before {background-position:0 -32px;}

.share a:before {background-position:0 -48px;}

.comment a:before {background-position:0 -64px;}

Providing hover, focus, active, and “saved” states is just a case of declaring the correct background position in each case.

增加hover, focus, active, 与 “.saved”的情况是为了让列表在这些情况下也能正确渲染背景位置。

.save a:hover:before,

.save a:focus:before,

.save a:active:before {background-position:-16px -16px;}

.saved a:before {background-position:-32px -16px;}

Future alternatives

In the future, there will be other alternatives. Firefox 3.6 added -moz-image-rect to allow background images to be cropped. But this is not supported by other browsers and looks likely to be replaced by an alternative proposal (to use fragment identifiers) that is part of the CSS Image Values Module Level 3 specification. As far as I know, no stable release of any modern browser supports the use of fragment identifiers with bitmap images.

将来的替代方案

将来可以用另一种方式来实现。火狐浏览器的私有属性 -moz-image-rect可以裁切背景。但这个属性不被其他浏览器支持,而且可能会被属于css3背景属性草案中的一个标识所取代。据我所知就位图图像而言,现代浏览器对于这个属性没有任何稳定的支持。

Emulating background-transform

Known support: Firefox 3.6+, Opera 10.5+, Safari 4+, Chrome 4+, IE 9+

模拟背景变换

Demo: Pseudo background-transform

Combining pseudo-elements and transforms makes it possible to emulate background transforms. A pseudo background-transform can be used to rotate, scale, and skew background images and sprites. There is no proposal for background-image transforms, so a pseudo-element hack is one way to emulate it.

结合伪元素与css3 transform可以模拟背景变换。可以使用rotate,scale,skew属性。目前没有提案要求支持背景变换属性,所以伪元素技巧是唯一可以模拟此效果的方法。

Example: rotating a background image

The example of cropping sprites can be further developed by reducing the number of different images used in the sprite. Rather than applying transforms to images in a graphics package, they can be applied in the CSS.

刚刚讲解的背景图片裁切技术可以减少精灵图中的图片个数。我们也可以用css来实现图片的变形,而不需要使用图形软件处理。

The code to do this is relatively simple and might look something like:

这里代码比较简单,类似以下的内容:

.accordion a:before {

   content:””;

   float:left;

   width:16px;

   height:16px;

   margin:0 5px 0 0;

   background:url(sprite.png) no-repeat 0 0;

}

.accordion.open a:before {

   -webkit-transform:rotate(90deg);

   -moz-transform:rotate(90deg);

   -ms-transform:rotate(90deg);

   -o-transform:rotate(90deg);

   transform:rotate(90deg);

}

To apply a transform to a more conventional background image (e.g., a large graphic sitting behind some content that doesn’t affect the positioning of other components) requires use of the positioning technique detailed in the article Multiple Backgrounds and Borders with CSS 2.1.

若想对背景图片应用变换,而不会影响到其他元素,需要使用定位来调整背景图片的位置,可以参考Multiple Backgrounds and Borders with CSS 2.1.

It involves setting the background image on a pseudo-element which is then positioned behind the content layer of an element using absolute positioning and z-index.

这里我们利用了伪元素,给伪元素使用图片,之后利用绝对定位跟z-index属性定位伪元素到内容层的下面即可。

Example: mirroring a background image

There are instances when mirroring a background image might be desired. The approach is similar to that for rotating an image, but this time usestransform:scale().

例子:背景图片倒影效果

有时候会对背景图有这样的需求,方法类似,不过这次使用的是transform:scale属性

Producing an exact mirror of an element or pseudo-element can be done using transform:scaleX(-1), transform:scaleY(-1), andtransform:scale(-1,-1) to mirror along the x-axis, y-axis, and both axes, respectively.

通过伪元素 利用transform:scaleX(-1), transform:scaleY(-1), transform:scale(-1,-1)  这三个属性你可以沿着x轴,y轴或者沿着中心轴做镜像对称。

The following code is an example of how a pseudo background-transform might be used for pagination links. A pseudo-element displays a single image (or region of a sprite) and is then mirrored. The image’s appearance is such that a rotation cannot produce the desired counterpart. Only a scale operation can do it.

下面的例子展示了伪元素模拟的背景变换是怎样应用在一个翻页链接上的。伪类显示了一张单独的图片,或者一张精灵图的一部分,之后进行变换。

注意rotation不能得到我们想要的效果,需要使用scale操作。

.prev a:before,

.next a:before {

   content:””;

   float:left;

   width:16px;

   height:16px;

   margin:0 5px 0 0;

   background:url(sprite.png) no-repeat 0 0;

}

.next a:before {

   float:right;

   margin:0 0 0 5px;

   -webkit-transform:scaleX(-1);

   -moz-transform:scaleX(-1);

   -ms-transform:scaleX(-1);

   -o-transform:scaleX(-1);

   transform:scaleX(-1);

}

There is no support for this in IE 8. Even if you’re a fan of using IE filters to work around some missing CSS support, they won’t work on pseudo-elements.

这个属性ie8以下不支持,即使你用ie的变换滤镜,伪元素上也不会生效。

Future alternatives

There don’t seem to be any future alternatives in any CSS working draft. For the moment, it looks like pseudo-element hacks will be needed to emulate effects like background transforms and background perspective without resorting to presentational HTML.

未来的解决方案

貌似css草案中没有相关的方案,你不需要依靠额外的标签,只需要伪元素就可以实现背景变换跟背景透视的效果。

Emulating background-position

Known support: Firefox 3.5+, Opera 10+, Safari 4+, Chrome 4+, IE 8+

模拟background-position

Demo: Pseudo background-position

The CSS 2.1 specification limits the values of background-position to offsets from the left and top sides. It’s possible to emulate positioning a background image from the right and bottom sides by applying the background image to a pseudo-element and using it as an additional background layer.

Css2.1的background-position属性计算图片偏移只能从元素左侧跟上侧开始计算。这里可以给伪元素设置背景图片,之后把伪元素作为附加的背景层,即可实现从右侧跟下侧来计算背景偏移了

This hack is easily combined with the other hacks in this article. More details on the pseudo background-position hack can be found in the article on Multiple Backgrounds and Borders with CSS 2.1.

这个技巧可以很容易的结合其他技巧使用。更多利用伪元素实现background-position的细节可以参考Multiple Backgrounds and Borders with CSS 2.1.

Example code

In this example, a pseudo-element is created and placed behind the element’s content layer. The background image is 500px × 300px and declared for the pseudo-element, which is also given dimensions that match those of the image. Since the pseudo-element is absolutely positioned, it can be positioned from the bottom and right of the element using offsets.

在这个例子里伪元素放置到内容层的下面。给伪元素设置的背景图片的大小是500px × 300px,因此我们也要设置伪元素的宽高。

利用绝对定位,我们也可以调整伪元素的位置。

#content {

   position:relative;

   z-index:1;

}

#content:before {

   content:””;

   position:absolute;

   z-index:-1;

   bottom:10px;

   right:10px;

   width:500px;

   height:300px;

   background:url(image.jpg);

}

Future alternatives

There is a part of the CSS Backgrounds and Borders module working draft that describes an improvement to the background-position property to allow positions to be set from any side. At the moment, Opera 11 is the only stable release of a browser that has implemented it.

这里的css草案 CSS Backgrounds and Borders module 增强了background-position的效果,使其可以从盒子模型的任何一侧开始计算。到现在为止opera11是唯一可以稳定支持这个属性的浏览器。

Emulating background-opacity

Known support: Firefox 3.5+, Opera 10+, Safari 4+, Chrome 4+, IE 9+

模拟背景透明度

Demo: Pseudo background-opacity

Changing the opacity of a pseudo-background is as simple as modifying the value of the opacity property. There is no IE 8 support for opacity and IE filters will not work on pseudo-elements.

改变伪元素的透明度跟直接操纵元素的透明度一样容易。

Ie8及以下利用滤镜对伪元素设置透明度是无效的

Example code

This example code shows a pseudo-element being created and positioned behind the rest of the element’s content so as not to interfere with it. The pseudo-element is then sized to fit the element using offsets (but could be offset by other values or given an explicit size), given a background image, and has its opacity changed.

示例代码

我们可以利用定位把伪元素定位在内容层下面,这样就不会影响内容了。之后利用坐标或者宽高调整伪元素的大小,使其适配内容。之后给伪元素设置背景图片,改变伪元素的透明度就可以了。

#content {

   position:relative;

   z-index:1;

}

#content:before {

   content:””;

   position:absolute;

   z-index:-1;

   top:0;

   bottom:0;

   left:0;

   right:0;

   background:url(image.jpg);

   opacity:0.7;

}

Notes

For now, and as far as I am aware, using CSS 2.1 pseudo-elements is the only widely supported (and backwards compatible) way to emulate background image crop, background transform, background opacity, and improved background positioning with semantic HTML.

Even when alternatives in CSS working drafts (e.g., the improvedbackground-position and use of fragment identifiers) are widely implemented, pseudo-element background-image hacks will still have the advantage of letting you use other CSS properties like opacity, border-radius, border-image, box-shadow, transforms, etc., which may prove useful in certain situations. It can’t hurt to be aware of these options.

It’s worth mentioning that although you can only generate 2 pseudo-elements from a DOM element, in many cases you can easily use descendant elements to provide more pseudo-elements to play with. This idea was used to help create the rotated example on the CSS drop-shadows demo page and several of the CSS3 examples at the bottom of the pure CSS speech bubbles demo page.

 

(译)css伪元素技巧》上有1条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>