20个实用的CSS技巧代码

大家非常的清楚CSS是我们Web制作中不可或缺的一部分。HTML提供了Web制作的结构,但他不能让我们实现美丽的页面制作,此时我们需要CSS的帮助。CSS虽然能帮我们完善Web制作的效果,但其在不同的浏览器下是有不可预知的效果,为了让你的CSS能解决这些不一致下,今天给大家介绍25个CSS技巧代码,我相信这些对你肯家有很大的作用。

一、使用text-indent来隐藏文本

这个常用在图片替换文本中,最常见的就是使用使用图片来替换Logo,这个是非常有用的,使用“text-indent”我们可以达到图片替换文本的效果,而且方便搜索引擎的优化,还能支持阅读器阅读网页内容:

			h1 {
				text-indent:-9999px;
				margin:0 auto;
				width:400px;
				height:100px;
				background:transparent url("images/logo.jpg") no-repeat scroll;
			}
		

当然,这个只是使用“text-indent"替换文本的一种效果,其实他还有更多的方法。

扩展阅读:

  1. 十种图片替换文本CSS方法
  2. Fahrner Image Replacement
  3. Revised Image Replacement
  4. A new image replacement technique
  5. Dynamic Text Replacement
  6. Using background-image to replace text
  7. CSS Hack: text-indent: -10000px;
  8. CSS text-indent: An Excellent Trick To Style Your HTML Form

二、根据文件格式设置链接图标

这个技巧主要是针对用户体验,让用户能很清楚点击的链接是有关于什么方面的内容,比如说,点击某个链接会到跳到站外。换句话说使用属性选择器器,给不同的链接设置不同的图标,让用户很轻松的明白相应的链接是有关于什么方面的内容:

			a[href^="http:"] {
					display:inline-block;
					padding-right:14px;
					background:transparent url(/Images/ExternalLink.gif) center right no-repeat;
			}
			a[href^="mailto:"] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/MailTo.gif) center left no-repeat;
			}
			a[href$='.pdf'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/PDFIcon.gif) center left no-repeat;
			}
			a[href$='.swf'], a[href$='.fla'], a[href$='.swd'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/FlashIcon.gif) center left no-repeat;
			}
			a[href$='.xls'], a[href$='.csv'], a[href$='.xlt'], a[href$='.xlw'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/ExcelIcon.gif) center left no-repeat;
			}
			a[href$='.ppt'], a[href$='.pps'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/PowerPointIcon.gif) center left no-repeat;
			}
			a[href$='.doc'], a[href$='.rtf'], a[href$='.txt'], a[href$='.wps'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/WordDocIcon.gif) center left no-repeat;
			}
			a[href$='.zip'], a[href$='.gzip'], a[href$='.rar'] {
					display:inline-block;
					padding-left:20px;
					line-height:18px;
					background:transparent url(/Images/ZIPIcon.gif) center left no-repeat;
			}
		

扩展阅读:

  1. 八个制作Linking(链接)的技巧
  2. Auto-matic Link Icons
  3. CSS 3 attribute selectors

三、在IE浏览器中删除textarea的滚动条

IE浏览器中textarea默认就有滚动条出现,为了达到所有浏览器默认下一致的效果,其实我们可以使用代码让他达到一致的效果:

			textarea{
				overflow:auto;
			}	
		

扩展阅读:

  1. Remove Scrollbar from Textarea in IE
  2. CSS Remove Textarea Scrollbar

四、段落首字下沉

有杂志排版中我们常看到第一个段落的首字下沉的效果,其实这种效果实现是相当的容易:

		p:first-letter{
			display:block;
			margin:5px 0 0 5px;
			float:left;
			color:#FF3366;
			font-size:60px;
			font-family:Georgia;
		}
	

扩展阅读:

  1. CSS Drop Cap Effect
  2. Drop Caps
  3. Drop Caps with CSS
  4. Creating drop caps using css
  5. CSS Drop Caps

五、所有浏览器下的CSS透明度

元素透明度时常是个恼人的问题,下面这种方式可以实现所有浏览器下的透明度设置:

		.transparent {
      zoom: 1;
      filter: alpha(opacity=50);
      opacity: 0.5;
		}
	

但是使用opacity会影响其后代元素的透明度,我们可以考虑使用:

		.transparent {
			/* Fallback for web browsers that doesn't support RGBa */
			background: rgb(0, 0, 0);
			/* RGBa with 0.6 opacity */
			background: rgba(0, 0, 0, 0.6);
			/* For IE 5.5 - 7*/
			filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
			/* For IE 8*/
			-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
		}
	

扩展阅读:

  1. CSS3 RGBA
  2. Cross-Browser Transparency via CSS
  3. CSS Opacity: A Comprehensive Reference
  4. HTML/CSS: Transparent iframes in All Browsers
  5. CSS Transparency Settings for All Browsers

六、Reset Css

Eric Meyer的重置CSS几乎已经成为标准,用来重置浏览器的默认样式:

		html, body, div, span, applet, object, iframe,
		h1, h2, h3, h4, h5, h6, p, blockquote, pre,
		a, abbr, acronym, address, big, cite, code,
		del, dfn, em, font, img, ins, kbd, q, s, samp,
		small, strike, strong, sub, sup, tt, var,
		b, u, i, center,
		dl, dt, dd, ol, ul, li,
		fieldset, form, label, legend,
		table, caption, tbody, tfoot, thead, tr, th, td {
			margin: 0;
			padding: 0;
			border: 0;
			outline: 0;
			font-size: 100%;
			vertical-align: baseline;
			background: transparent;
		}

		body {
			line-height: 1;
		}

		ol, ul {
			list-style: none;
		}

		blockquote, q {
			quotes: none;
		}

		blockquote:before, blockquote:after,
		q:before, q:after {
			content: '';
			content: none;
		}

		/* remember to define focus styles! */
		:focus {
			outline: 0;
		}

		/* remember to highlight inserts somehow! */
		ins {
			text-decoration: none;
		}

		del {
			text-decoration: line-through;
		}

		/* tables still need 'cellspacing="0"' in the markup */
		table {
			border-collapse: collapse;
			border-spacing: 0;
		}
	

但这样的重置样式并非适合每一个人,我就在此基础上精减了部分代码,因为我发现我们有很多标签是不怎么使用的:

		body,ul,ol,dl,dd,dir,h1,h2,h3,h4,h5,h6,p,pre,blockquote,hr,figure{
      margin:0;
      padding:0;
      font-size: 100%;
      vertical-align:baseline;
		}

		table {
			border-collapse:collapse;
			border-spacing:0;
		}

		article, aside, dialog, figure, footer, header, hgroup, nav, section { 
			display:block;
		}

		/*
		 * Corrects inline-block display not defined in IE6/7/8/9 & FF3
		 */

		audio,
		canvas,
		video {
			display: inline-block;
			*display: inline;
			*zoom: 1;
		}

		/*
		 * Prevents modern browsers from displaying 'audio' without controls
		 */

		audio:not([controls]) {
			display: none;
		}

		/*
		 * Addresses styling for 'hidden' attribute not present in IE7/8/9, FF3, S4
		 * Known issue: no IE6 support
		 */

		[hidden] {
			display: none;
		}
	

扩展阅读:

  1. Killer Collection of CSS Resets
  2. * { CSS:resetr }
  3. An (Almost) Complete List of Global CSS Reset Styles
  4. 目前比较全的CSS重设(reset)方法总结
  5. CSS Tools: Reset CSS
  6. HTML5 Reset
  7. Reset CSS研究(八卦篇)
  8. No CSS Reset

七、图片预加载

图片预加载有时是非常有用的,这样当某个元素需要时,他就已经被加载了,此时就不会有任何延误或闪烁的现像:

		#preloader {
			/* Images you want to preload*/
			background-image: url(image1.jpg);
			background-image: url(image2.jpg);
			background-image: url(image3.jpg);
			width: 0px;
			height: 0px;
			display: inline;
		}
	

扩展阅读:

  1. 3 Ways to Preload Images with CSS, JavaScript, or Ajax
  2. Image Preloader
  3. CSS Image Preloader
  4. Creating a CSS Image Preloader
  5. Image Preloader
  6. Tutorial: How to add preloader with loading image in a gallery using jQuery
  7. jQuery Plugin: Preload Images
  8. 4 Ways To Preload Images With CSS or JavaScript

八、基本的CSS Sprite按钮

CSS Sprite我想大家一定是非常熟悉,我们时常在按钮或链接中使用CSS Sprites,用来提搞用户的体验。比如说,我们有一个按钮,当用户鼠标在按钮上时需要显示另一种背景,那么我们就可以使用这样的技术:

		a {
			display: block;
			background: url(sprite.png) no-repeat;
			height: 30px;
			width: 250px;
			}

		a:hover {
			background-position: 0 -30px;
		}
	

扩展阅读:

  1. CSS Sprites: Image Slicing’s Kiss of Death
  2. The Mystery Of CSS Sprites: Techniques, Tools And Tutorials
  3. CSS Sprites: What They Are, Why They’re Cool, and How To Use Them
  4. Basic Link Rollover as CSS Sprite
  5. Resizable Buttons Using CSS Sprites
  6. Create a Button with Hover and Active States using CSS Sprites
  7. Perfect CSS Sprite / Sliding Doors Button
  8. simple css sprites
  9. Designing CSS Buttons: Techniques and Resources

九、Google Font API

Google Font给我们提供一个新的字体设置:

		<head>
			Inconsolata:italic|Droid+Sans"
		</head>
	
		body {
			font-family: 'Tangerine', 'Inconsolata', 'Droid Sans', serif; font-size: 48px;
		}
	

扩展阅读:

  1. Google Web Fonts API
  2. Google web fonts
  3. A Guide to Google Font API
  4. Google Font API
  5. Google Font API and Typekit solutions VS @font-face
  6. Quick Tip: Google Fonts API: You’re Going to Love This
  7. The Google Font API for Web Developers
  8. Easy Custom Web Typography with Google Fonts API

十、浏览器的专用hack

浏览器的兼容问题向来都是很烦的事情,特别是在IE下的兼容问题。但有时我们为了达到一致的效果,不得不使用浏览器的兼容:

		/* IE 6 */
		* html .yourclass { }

		/* IE 7 */
		*+html .yourclass{ }

		/* IE 7 and modern browsers */
		html>body .yourclass { }

		/* Modern browsers (not IE 7) */
		html>/**/body .yourclass { }

		/* Opera 9.27 and below */
		html:first-child .yourclass { }

		/* Safari */
		html[xmlns*=""] body:last-child .yourclass { }

		/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
		body:nth-of-type(1) .yourclass { }

		/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
		body:first-of-type .yourclass {  }

		/* Safari 3+, Chrome 1+ */
		@media screen and (-webkit-min-device-pixel-ratio:0) {
		 .yourclass  {  }
		}
	

扩展阅读:

  1. 浏览器兼容之旅的第二站:各浏览器的Hack写法
  2. Browser-Specific CSS Hacks
  3. Browser Specific Hacks
  4. Browser CSS hacks
  5. Browser Specific Hacks
  6. CSS Browser Selector
  7. Css Hacks

十一、固定页脚

固定页脚在屏幕的底部,在现代浏览器来说是一件非常容易的事情,但是在IE6下还是需要特殊的处理:

		#footer {
			position:fixed;
			left:0px;
			bottom:0px;
			height:30px;
			width:100%;
			background:#999;
		}

		/* IE 6 */
		* html #footer {
			position:absolute;
			top:expression((0-(footer.offsetHeight)+(document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px');
		}
	

扩展阅读:

  1. Fixed footer
  2. Fixed Footer
  3. Development: Fixed Footers without JavaScript
  4. Fixed Footer Backgrounds with CSS
  5.  
  6. Fixed Header & Footer Layout: A Beginner’s Guide
  7. CSS Fixed Footer
  8. SharePoint 2010 – Adding a Fixed Footer to your SharePoint Master Page

十二、翻转图片

翻转图像随着CSS3的transform越来越实用,不需要重新加载图片,就可以实现一个图片的旋转。常见的是一个三角型效果,我们想让他在不同状态展示不同的风格:

		img.flip {
			-moz-transform: scaleX(-1);
			-o-transform: scaleX(-1);
			-webkit-transform: scaleX(-1);
			transform: scaleX(-1);
			filter: FlipH;
			-ms-filter: "FlipH";
		}
	

扩展阅读:

  1. Flip an Image

十三、clearfix

clearfix主要是使用他来清除浮动,只需要添加这个类名无需加上任何HTML标记,就可以达到清除浮动的效果:

		.clearfix:before,
		.clearfix:after {
			content: " ";
			display:table;
		}

		.clearfix:after {
			clear:both;
			overflow:hidden;
		}
		.clearfix { 
			zoom: 1;
		}
	

扩展阅读:

  1. Clear Float
  2. Force Element To Self-Clear its Children
  3. CSS Clearfix Best Cross browser solution
  4. Lessons Learned Concerning the Clearfix CSS Hack
  5. A new micro clearfix hack
  6. How To Clear Floats Without Structural Markup

十四、圆角

随着CSS3的属性的出现,我们制作圆角效果就不需要在像以前那样的辛苦了,可以使用CSS3的border-radius来实现,只是在IE-6-8下无法实现,我们来看现代浏览器下如何制作圆角:

		.round{
			-moz-border-radius: 10px;
			-webkit-border-radius: 10px;
			-khtml-border-radius: 10px; /* for old Konqueror browsers */
			border-radius: 10px; /* future proofing */
		}
	

扩展阅读:

  1. CSS3的圆角Border-radius
  2. Rounded Corners
  3. CSS Rounded Corners 'Roundup'
  4. CSS Rounded Corners In All Browsers (With No Images)
  5. CSS Rounded Corners
  6. Rounded Corners
  7. CssRound : the rounded corner Css3 generator

十五、!important

!important有时可以帮我们做很多事,他可以覆盖任何相同的样式,换句话说他可以改为样式的权重:

		p{
			font-size:20px !important;
		}
	

扩展阅读:

  1. !important CSS Declarations: How and When to Use Them
  2. When Using !important is The Right Choice
  3. Using !important with CSS
  4. The importance of !important in CSS
  5. Override Inline Styles with CSS
  6. IE6 and the !important rule

十六、@font-face

@font-face也是CSS3的属性之一,他能在所有浏览器下运行。最大的作用就是让用户没有字体的浏览下也能支持网页字体,具体使用:

		@font-face {
			font-family: 'Graublau Web';
			src: url('GraublauWeb.eot');
			src: local('☺'),
				url('GraublauWeb.woff') format('woff'), url('GraublauWeb.ttf') format('truetype');
		}
		h2 {
			font-family:'Graublau Web';
		}
	

扩展阅读:

  1. CSS3 @font-face
  2. CSS3 @font-face Design Guide
  3. CSS @ Ten: The Next Big Thing
  4. CSS3 Trans­forms & @font-face Experiment.
  5. 35 Best CSS3 @font-face Kits
  6. CSS3 @Font Face
  7. @font-face

十七、页面水平居中

如何使一个网站的页面水平居中显示,我想这个不用我说大家也知道,因为大家肯定使用过多次了。

		.wrapper {
			width:960px;
			margin:0 auto;
		}
	

扩展阅读

  1. Horizontally Center Your Website Structure Using CSS
  2. How to Center a Website With CSS
  3. Centering Your Web Site With CSS
  4. How to center content using CSS
  5. CSS Centering – fun for all!
  6. Absolute Center (Vertical & Horizontal) an Image

十八、最小高度min-height

在IE6浏览器下是不支持最小高度这个属性的,为了解决这个问题,我们可以使用下面这样的代码来处理:

		.box {
			min-height:500px;
			height:auto !important;
			height:500px;
		}
	

扩展阅读

  1. Prop-Clear: CSS min-height hack
  2. min-height
  3. Cross-Browser Min Height
  4. min and max
  5. CSS layout: 100% height with header and footer

十九、垂直居中

水平居中处理起来相当的简单的,但是垂直居中处理起来还是相当的烦,特别是要兼容IE的浏览器情况下:

		<p>CAN HAS VERTICAL CENTER?</p>
    <p>
      <img src="/pics/smiley.png" alt="Lorem Ipsum" height="35" width="35">
      <span class="for_ie6"></span>
        CAN HAS VERTICAL CENTER?
    </p>
	
		div {
			height: 100px;
			line-height: 100px;
			white-space: nowrap;
		}

		img { vertical-align: middle; }

		.for_ie6 { display: inline-block; }
		.for_ie6 { display: inline; }
	

扩展阅读

  1. CSS制作水平垂直居中对齐
  2. Vertical Centering in CSS
  3. Vertically center content with CSS
  4. How to: vertical centering with CSS is a post on The Hickensian
  5. Vertical Centering
  6. 6 Methods For Vertical Centering With CSS
  7. Vertical centering using CSS
  8. Centering things

二十、::selection

有很多朋友肯定不知道这个属性的作用。它可以改变选择的文本的背景色和前景色,突出你的浏览器中的选择文本效果:

		::selection {
			color: #000000;
			background-color: #FF0000;
		}
		::-moz-selection {
			color: #000000;
			background: #FF0000;
		}
	

扩展阅读

  1. CSS ::Selection
  2. Overriding The Default Text Selection Color With CSS
  3. CSS3 Tutorial: How To Change Default Text Selection Colour
  4. selection styles

上面给大家展示了二十种CSS技巧代码片段,我知道我还没有能够覆盖每一个有用的CSS技巧代码片段,但我搜集这些代码片段,只是希望对有需要的朋友有所帮助。如果你有其他更好的CSS技巧片段,希望在下面的评论中留下与大家共享。

如需转载烦请注明出处:W3CPLUS

返回顶部