日期:2014-05-16  浏览次数:20675 次

一些上流的CSS3图片样式
译自:CSS3 Image Styles
中文:CSS3图片样式
请尊重版权,转载请注明来源,多谢~~

直接在图片元素上直接应用CSS3 inset box-shadow 或 border-radius时,浏览器并不能完美的渲染它们。不过,如果把这个图片用作背景图,你就可以可以给它添加任何样式了,浏览器也会很好地渲染。Darcy Clarke和我做了一个简单的教程,讲解如何使用jQuery来动态地制作完美的圆角图片。今天我将重温这个主题然后向你展示使用background-image的方法可以实现多少效果。我将向你展示如何使用box-shadow、border-radius 和 transition 来创作不同的图片风格。

?

先看下demo

?

问题 (见 demo)

看一下demo,请注意在第一行的图片中使用了border-radius和inset box-shadow。Firefox会直接在图片元素上渲染border-radius,但不会渲染inset box-shadow。chrome/safari则两者都不渲染。

border-radius problem

?

解决方案

要让 border-radius 和 inset box-shadow 正常工作,解决方案就是将实际图片变作background-image.

code

?

动态方法

要想动态实现,可以简单的使用jQuery为每个图片元素外面包一个背景图片。下面的jQuery代码会将所有图片外面包一个span标签然后将图片用作其背景图片(jQuery代码由Darcy Clarke编写)。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 
	$("img").load(function() {
		$(this).wrap(function(){
			return '<span class="image-wrap ' + $(this).attr('class') + '" 
				style="position:relative; display:inline-block; background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
		});
		$(this).css("opacity","0");
	});
});
</script>
?

?

输出

上面的脚本将会输出下面的HTML代码:

<span class="image-wrap " style="position:relative; display:inline-block; background:url(image.jpg) no-repeat center center; width: 150px; height: 150px;">
	<img src="image.jpg" style="opacity: 0;">
</span>
?

?

圆形图片(见 demo)

现在,图片被用作背景图了,你可以给它添加任意你想要的样式上去。下面是一个简单的使用border-radius实现的圆形图片。如果你对CSS3不太了解,可以阅读下Basics of CSS3,也可以搜索一下前端观察。

circle image

CSS

.circle .image-wrap {
	-webkit-border-radius: 50em;
	-moz-border-radius: 50em;
	border-radius: 50em;
}

?

卡片风格(见 demo)

下面是一个像卡片的图片风格,用了多个inset box-shadow。

card style

CSS

.card .image-wrap {
	-webkit-box-shadow: inset 0 0 1px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -1px 0 rgba(0,0,0,.4);
	-moz-box-shadow: inset 0 0 1px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -1px 0 rgba(0,0,0,.4);
	box-shadow: inset 0 0 1px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -1px 0 rgba(0,0,0,.4);
 
	-webkit-border-radius: 20px;
	-moz-border-radius: 20px;
	border-radius: 20px;
}

?

浮雕风格 (见 demo)

通过一点儿改变,我可以将卡片风格转换为浮雕。。。

embossed image

CSS

.embossed .image-wrap {
	-webkit-box-shadow: inset 0 0 2px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -7px 0 rgba(0,0,0,.6), inset 0 -9px 0 rgba(255,255,255,.3);
	-moz-box-shadow: inset 0 0 2px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -7px 0 rgba(0,0,0,.6), inset 0 -9px 0 rgba(255,255,255,.3);
	box-shadow: inset 0 0 2px rgba(0,0,0,.8), inset 0 2px 0 rgba(255,255,255,.5), inset 0 -7px 0 rgba(0,0,0,.6), inset 0 -9px 0 rgba(255,255,255,.3);
 
	-webkit-border-radius: 20px;
	-moz-border-radius: 20px;
	border-radius: 20px;
}

?

软浮雕风格 (见 demo)

和浮雕风格真的很像,我只是加了1px的虚化~~

soft embossed

CSS