# 超实用的css代码段_快速启动您的项目：便捷CSS代码段集合

In one of the previous articles “Basic Ready-to-Use CSS Styles”, we saw how we could create a suite of classes to help the design process while making a website. I hope you made your own set of patterns!

Today we are going to see how we can continue this exercise with some things a little bit more technical. I’ll show you a bunch of CSS snippets you may or may not know, which can dramatically increase your CSS development speed.

Indeed, isn’t there some properties or CSS tricks you always have to check the syntax for, every single time you want to use them? Don’t you ever want to have some kind of way to avoid endlessly repeating the same lines of code?

Of course you do my friends! We will see how we can fix all of this. And in the meantime, we will briefly introduce some very useful mixins for those of you who are digging into CSS preprocessors. What do you say? Ready?

Before we go, let me tell you how I divided this article:

### 速记班 (Shorthand classes)

Let’s begin with shorthand classes, which are a very common things. The point is to allow you to quickly do this or that without struggling to target your element with crazy town selectors.

The best example is probably the one where you have some text and an image you want to include on the left side of the text. You can either target the image directly in the context (class/ID) or use one of your awesome shorthand classes:


.float-left /* Or whatever name you like */ {
float: left;
}

.float-right /* Or whatever name you like */ {
float: right;
}



Nothing more. Back to our example: you are building your markup until you have to insert an image. Easy peasy, you simply add the .float-left class to the image, and it’s done. Now you can go back to your CSS file with class/ID targeting and such. Maybe another example?


.hide {
display: none;
}

.show {
display: block;
}



You want to hide or show some of your elements for some reason. Instead of targeting an element directly and add display: none, you simply give it the .hide class.

This can also make your JavaScript development a lot easier. Imagine, you want to show those X items you set to display: none? You can now simply target all elements with the .hide class.

I think you get the point of these shorthand classes. They are not much than just a single CSS property, but thanks to them, you don’t have to go back to your CSS files and struggle with CSS selectors.

### 与设计有关的摘要 (Design-related snippets)

If you have read “Basic Ready-to-Use CSS Styles”, you already know some examples of design-related snippets. Those are little classes you can easily set to your elements in order to make the design process lighter and simpler, and to keep some kind of common style. Let’s dig a little bit into it, shall we?

Let’s start with something you’ll need in pretty much every single project you’ll ever work on: font styles. Creating some appealing combination of font-size, line-height and fonts can be tricky. Let’s make a few that will easily cascade through our document.


.content {
font: 1em/1.4 Segoe, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}

.title {
font: 1.7em/1.2 Baskerville, "Baskerville old face", "Hoefler Text", Garamond, "Times New Roman", serif;
}

.code {
font: 0.8em/1.6 Monaco, Mono-Space, monospace;
}



This snippet does a few things:

• First, it changes the default font styles for your main content. The idea is to apply this to the root element in order to let it cascade to all elements.

首先，它将更改主要内容的默认字体样式。 想法是将其应用于根元素，以便使其级联到所有元素。
• Second, it gives some emphasize to any element with the .title class with a classy serif font. Adapt it to suit your needs.

其次，它强调了.title类中具有经典衬线字体的任何元素。 对其进行调整以适合您的需求。
• Last, it gives code elements (inline or block) some special styles with a monospace font and a smaller font size.

最后，它为代码元素(内联或块)提供了一些特殊样式，这些样式具有等宽字体和较小的字体大小。

It may seem silly, but it can be a huge time saver when you don’t want to specify font styles every single time you use a new element. Just add the according class, and let the cascade do the rest.

Maybe something a bit more practical now: a “disabled” class. “What for”, you ask? Whenever you want to show something is being disabled simply add the .disabled class (or whatever you’d like to call it). First of all, it will turn its opacity to 0.5, but more importantly, it will disable all pointer events on it (hover, click, etc.).


.disabled {
pointer-events: none;
opacity: 0.5;
}



A live example would be to give this class to the submit button of a form as a default. When every required field is properly filled, remove this class with JavaScript. Clean and simple, it helps the user understand he did everything right.

Important: don’t forget to add some server side verification. CSS and JavaScript can easily be manipulated. 😉

Another very easy example taking advantage of powerful CSS selectors would be the well known snippet which will give tables a Zebra look:


table tr:nth-child(even) {
background: rgba(0,0,0,0.1);
}



Note: you could also use the odd keyword for the nth-child property to target odd numbers. And of course you can pick whatever color you want. 😉

The last snippet example directly affecting design: some improved link styling.


a {
text-decoration: none;
color: #08C;
transition: all 0.3s ease-out;
position: relative;
margin: -.5em;
}

a:hover { color: #0AF; }



We just did four things here:

• We removed the default underline by setting text-decoration to none.

通过将text-decoration设置为none我们删除了默认的下划线。

• We changed the color to a different yummier blue!

我们将颜色更改为其他的yummier蓝色！
• We added a CSS transition to make the move to the hover state easier (remember to add vendor prefixes).

我们添加了CSS过渡，以使移至悬停状态更加容易(请记住添加供应商前缀)。
• We used this awesome technique from Joshua Hibbert to increase the clickable area on links. This is especially useful when it comes to mobile navigation, where clicking links can be tricky.

我们使用了约书亚·希伯特(Joshua Hibbert)的这项出色技术来增加链接上的可点击区域。 当涉及到移动导航时，这尤其有用，因为单击链接可能很棘手。

### 与开发相关的摘要 (Development-related snippets)

In the last section, we saw a few snippets which may be considered as design improvements. It means your design won’t break or look crappy if you omit them but it will look nicer if you use them. In this section, we will have a look at CSS snippets which are a less “design-related” but more related to the structure or development-related. Hard to tell, best explained with examples. So let’s go.

The first example is very easy. You’ve probably seen it many times before, especially since Paul Irish encouraged people to use it a while back:


*, *:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}



In case you don’t know what the box-sizing property does: it’s used to alter the default box-model used to calculate widths and heights of elements. The default box-model is set to “content-box” which means it does not include padding and borders into the width value. This can be a huge pain in the butt, especially when it comes to responsive web design so we use a clean box-model: border-box.

A great example of using this would be to set some element’s width to 100% and add lateral padding to it. The default box-sizing would make the width be 100% plus the padding but using border-box would include the padding in the width. You can read more about it in this W3C working draft: CSS Basic User Interface Module Level 3 (CSS3 UI)

If you’re wondering about browser support, it is supported in every major browser, mobile ones included, excepted for Internet Explorer 7 and prior. A polyfill for those browsers exists if needed.

Note: it turns out that pseudo-elements are not included in the universal selector, so if you want your pseudo-elements to have a proper box-model like everything else, you should include them in the declaration.

Let’s continue with another very popular one: the clearfix. You know the song: when an element only contains floated elements, it collapses on itself. To prevent this behavior, you have to “clearfix” it. We used to do it with an extra element, but not anymore.


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

.clearfix:after {
clear: both;
}

/* IE6/7 support */
.clearfix {
*zoom: 1;
}



Note: The space content is one way to avoid an Opera bug when the contenteditable attribute is included anywhere else in the document. Otherwise it causes space to appear at the top and bottom of elements that are clearfixed.

Note: The use of display: table rather than display: block is only necessary if using the :before pseudo-element to contain the top-margins of child elements.

Enough with the common stuff, let’s get to something a little bit more underground!


.visuallyhidden {
position: absolute;
width: 1px; /* Setting this to 0 make it invisible for VoiceOver */
height: 1px; /* Setting this to 0 make it invisible for VoiceOver */
margin: -1px;
border: 0;
clip: rect(0 0 0 0);
overflow: hidden;
}



This is the “visually hidden” class taken from the HTML5BoilerPlate project. What’s the point when we have display: none you ask?

Setting display: none hides content for screen readers and search engine bots. This is the difference that really matters. When you’re making tabs or playing with slideToggle(), don’t hide the content with display: none because you will make it unavailable for both, screen readers and search bots. Instead give it the previous class.

Note: as a further reading, I recommend this article from CSS-Tricks: Places It’s Tempting To Use Display: None; But Don’t.

While we are talking about hiding stuff, let’s deal with image replacement. We all know what image replacement is:

1. Take an element

拿一个元素
2. Give it a background-image

给它一个背景图片
3. Hide the text

隐藏文字

Some of you have probably done this with position: absolute; left: -9999px; since the dawn of time. Yes, it works. But it’s incredibly heavy for the browser to create a 10000px box, so here is a “new” way of doing it by Scott Kellum:


.ir {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}



When you look at the code, this is incredibly clever. It only moves the text out of the box. Nothing more, nothing less.

Now we will see two snippets about long strings truncation: one preventing the text to break out of their container (such as an URL) by forcing the break. And one to make an ellipsis in case the string is too long for its container.


.break {
-ms-word-break: break-all;
word-break: break-all;

word-break: break-word;

-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}

.ellipsis {
width: 250px;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis; /* Required for IE8 */
-o-text-overflow: ellipsis; /* Required for Opera */
text-overflow: ellipsis;
}



The first snippet (.break) works in Internet Explorer 8+, Firefox, Safari and Chrome. Sadly, it doesn’t work in Opera as far as I can tell. 🙁

The second snippet (.ellipsis) works in Internet Explorer 8+, Safari, Opera and Chrome. Sadly, it doesn’t work in Firefox. However, a clever guy found a way to do it with some XML and the -moz-binding property.

Note: set the width of the .ellipsis element to suit your needs.

And to end this section while we are talking about text and co., let’s see how to make long strings break in <pre> tags.


pre {
white-space: pre-wrap;       /* Chrome & Safari */
white-space: -moz-pre-wrap;  /* Mozilla since 1999 */
white-space: -pre-wrap;      /* Opera 4-6 */
white-space: -o-pre-wrap;    /* Opera 7 */
word-wrap: break-word;       /* Internet Explorer 5.5+ */
}



This is from an older article from Tyler Longren where the author doesn’t talk much about Opera 8+. I made some searches, and it looks like Opera supports the word-wrap property so it should work like a charm.

### 杂 (Miscellaneous)

For lack of a better name, I called this section “Miscellaneous”. It will contain various tips that you may or may not find useful depending on the project you’re working on.

Let’s start with a few rules for print. Yes, I know most of you won’t care much about making your website look cool when printed but there are some projects where you have to, so:


@media print {
* {
background: none !important;
color: black !important;

/* Images, vectors and such */
filter: Gray(); 						 /* IE4-8: depreciated */
filter: url('desaturate.svg#grayscale'); /* SVG version for IE10, Firefox, Safari 5 and Opera */
-webkit-filter: grayscale(100%); 		 /* Chrome + Safari 6 */
-moz-filter: grayscale(100%); 			 /* Future proof */
-ms-filter: grayscale(100%); 			 /* Future proof */
-o-filter: grayscale(100%); 			 /* Future proof */
filter: grayscale(100%); 				 /* Future proof or polyfilled */
}

a {
text-decoration: underline;
}

a[href]:after {
content: " (" attr(href) ")";
}

a[href="#"],
a[href="javascript:"] {
content: "";
}
}



<!-- SVG version of grayscale filter: desaturate.svg -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<filter id="grayscale">
<feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0  0  0  1 0"/>
</filter>
</svg>



Okay, there are many things to note here. Let’s start with the color stuff. You have probably understood the point of turning everything into black and white: saving money. Do you know how much a color ink cartridge costs? 😀

• The first four lines take care of 75% of the job by turning the font color to black and removing backgrounds and shadows.

前四行通过将字体颜色变为黑色并去除背景和阴影来完成75％的工作。
• The filter stuff mostly takes care of images by desaturating them. Internet Explorer uses an old proprietary filter, Chrome supports new CSS3 filters and for the others there is SVG.

过滤器材质通常通过使图像去饱和来处理图像。 Internet Explorer使用了旧的专有过滤器，Chrome支持新CSS3过滤器，其他的则是SVG。
• A few days ago Christian Schaefer released a JavaScript polyfill for CSS filters using the unprefixed syntax getting back to Internet Explorer 6 (!).

几天前，Christian Schaefer使用无前缀的语法发布了用于CSS过滤器JavaScript polyfill，返回Internet Explorer 6(！)。

• Since we removed colors, we’re back to the old-fashion way to show links: with an underline.

由于我们删除了颜色，因此我们回到了显示链接的老式方式：带下划线。
• If anchors have a href attribute (and they should), we show their content after them.

如果锚点具有href属性(并且应该具有)，我们将在其后显示其内容。

• But not if it’s a JavaScript or an empty link.

但如果是JavaScript或空链接，则不会。

Note: HTML5BoilerPlate provides a very powerful print style sheet.

Enough with the print. Let’s talk about something very trendy. Yes, you know what I’m talking about: retina displays! You know, those sweet little devices with a high resolution forcing us to recreate all of ours images twice as big. 🙂

Anyway, you may want to target only retina displays with CSS in order to, let’s say, override background images, or similar. There you go:


@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2), /* Looks like a bug, so may want to add: */
only screen and (   -moz-min-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {
/* Your retina specific stuff here */
}



Note: Chris Coyier recently updated his blog post about it so you may want to have a look at it.

Last, for the miscellaneous section, a CSS diagnostic snippet. Maybe you haven’t heard about it so much since it’s not really common. The idea, is to provide a block of code you activate when you want to do a little “validation” of your markup. Eric Meyer and Neil Grosskopf have provided some excellent resources.


/* Empty Elements */
.debug div:empty, .debug span:empty,.debug li:empty,.debug p:empty,.debug td:empty,.debug th:empty {
border: 5px dotted yellow !important;
}

/* Empty Attributes */
.debug *[alt=""], .debug *[title=""], .debug *[class=""], .debug *[id=""], .debug a[href=""] {
border: 5px solid yellow !important;
}

/* Deprecated Elements */
.debug applet, .debug basefont, .debug center, .debug dir, .debug font, .debug isindex, .debug menu, .debug s, .debug strike, .debug u {
border: 5px dotted red !important;
}

/* Deprecated Attributes */
.debug *[background], .debug *[bgcolor], .debug *[clear], .debug *[color], .debug *[compact], .debug *[noshade], .debug *[nowrap], .debug *[size], .debug *[start],.debug *[bottommargin], .debug *[leftmargin], .debug *[rightmargin], .debug *[topmargin], .debug *[marginheight], .debug *[marginwidth], .debug *[alink], .debug *[link], .debug *[text], .debug *[vlink],.debug *[align], .debug *[valign],.debug *[hspace], .debug *[vspace],.debug *[height], .debug *[width],.debug ul[type], .debug ol[type], .debug li[type] {
border: 5px solid red !important;
}

/* Proposed Deprecated Elements */
.debug input[type="button"], .debug big, .debug tt {
border: 5px dotted #33FF00 !important;
}

/* Proposed Deprecated Attributes */
.debug *[border], .debug table[cellpadding], .debug table[cellspacing] {
border: 5px solid #33FF00 !important;
}



Basically, you add the .debug class to the root of the document (the html element) and depending on your markup, you may see some elements bordered. From there, you decide what to do. 😉

Important: this doesn’t guarantee you to have a valid markup. In order to do this, please use the W3C validator.

Note: to improve the quality of your CSS, please have a look at CSSLint.

### Mixins(CSS预处理器) (Mixins (CSS preprocessors))

In the first part of this tutorial, we saw a lot of things you can add in your style sheet in order to ease the development process. I think it’s time to have a slight glance at CSS preprocessors-related snippets.

Important: I won’t explain in detail what CSS preprocessors are, nor will I try to convince you to use one, or use a specific one.

A CSS preprocessor allows you to use variables, mixins, functions, operations, nesting, importing and much more. For that concern, I personally use LESS but there are also Sass or Stylus which might fit your needs.

CSS预处理器允许您使用变量，混合，函数，操作，嵌套，导入等。 为此，我个人使用了LESS，但是也有SassStylus可以满足您的需求。

Anyway, I’m only going to talk about mixins here. Mixins are like variables but for whole classes. The best point of mixins is that they can behave like functions and have parameters.

Let’s start with something very simple: a mixin to handle all vendor prefixes whenever you want to apply a transform to an element.


.transform(@string) {
-webkit-transform:  @string;
-moz-transform: 	@string;
-ms-transform: 		@string;
-o-transform: 		@string;
transform: 			@string;
}



Okay, that was just to show you the idea. Maybe we could build a mixin for every kind of transform? Or at least the most used ones?


.rotate(@deg) {
-webkit-transform:  rotate(@deg);
-moz-transform: 	rotate(@deg);
-ms-transform: 		rotate(@deg);
-o-transform: 		rotate(@deg);
transform: 			rotate(@deg);
}

.scale(@factor) {
-webkit-transform:  scale(@factor);
-moz-transform: 	scale(@factor);
-ms-transform: 		scale(@factor);
-o-transform: 		scale(@factor);
transform: 		 	scale(@factor);
}

.translate (@x, @y) {
-webkit-transform:  translate(@x, @y);
-moz-transform: 	translate(@x, @y);
-ms-transform: 		translate(@x, @y);
-o-transform: 		translate(@x, @y);
transform: 		 	translate(@x, @y);
}



The only point of those mixins is to avoid writing vendor prefixes. Let’s go up a level.


.transition(@string: all 0.3s ease-out) {
-webkit-transition: @string;
-moz-transition: 	@string;
-ms-transition: 	@string;
-o-transition: 		@string;
transition: 		@string;
}



What does this mixin do exactly? It takes as a value all 0.3s ease-out if no value is specified. This is where it’s getting interesting. From now on (unless I want a very specific transition) I don’t have to set a value to transition anymore. I only have to do this:


.my-element {
.transition;
}

/* Output CSS */

.my-element {
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}



Another example would be to create a mixin that handles the box-sizing property with a default parameter. Something like:


.box-sizing(@value: border-box) {
-webkit-box-sizing: @value;
-moz-box-sizing:	@value;
-box-sizing: 		@value;
}

*, *:before, *:after {
.box-sizing;
}

/* Output CSS */

*, *:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}



We often associate preprocessors with CSS3, mostly because of the power of these previous examples, but you can of course, do perfectly valid CSS2.1 with preprocessors and find plenty of cases where you might “need” them. Please, have a look at the following code:


.placement(@top, @right, @bottom, @left) {
top: @top;
right: @right;
bottom: @bottom;
left: @left;
}

.my-element {
position: absolute;
.placement(0, 0, 0, 0);
}

/* Output CSS */

.my-element {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}



How cool is that? I’ve waited for ages to have a shorthand for this. I always found it annoying to have to type the 4 placement properties over and over again. We could even tweak it to include the type of position.


.placement(@type, @top, @right, @bottom, @left) {
position: @type;
top: @top;
right: @right;
bottom: @bottom;
left: @left;
}

.my-element {
.placement(absolute, 0, 0, 0, 0);
}

/* Output CSS */

.my-element {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}



I’d like to end with a very useful mixin mixing (see what I did there?) CSS2.1 and CSS3 in order to provide something which could be very annoying to do manually: a rem/px converter.

Rem stands for “root em”. Its behavior is similar to the em unit except that it’s relative to the root element, not its parent element. Every major browser now supports it except Opera Mini and Internet Explorer 6/7. For those browsers, we have to provide a fallback in px.

Rem代表“ root em”。 它的行为与em单元相似，除了它是相对于根元素而不是其父元素而言。 现在，除Opera Mini和Internet Explorer 6/7之外，所有主流浏览器都支持它。 对于这些浏览器，我们必须以px为单位提供备用。


.font-size(\$pxValue){
@remValue: (@pxValue / 10);
font-size: ~"@{pxValue}px";
font-size: ~"@{remValue}rem";
}

html { font-size: 62.5%; }

.my-element {
.font-size(13px);
}

/* Output CSS */

.my-element {
font-size: 13px;   /* Internet Explorer 6/7/8 + Opera Mini */
font-size: 1.3rem; /* Other browsers */
}



Basically, you set the font-size you want in pixels, and it gives you both px and rem. Easy peasy, end of story.

Note: the font-size: 62.5% thing on the html element is for switching to base 10 for the ease of calculations (default 16px * 62.5 / 100 = 10). From there, it’s easy to say 1.3rem + 13px.

### 最后的话 (Final words)

As a final word, I will encourage you to create your own CSS snippets, whatever they are, as long as they increase your productivity and ease of development. Be sure to share them! 😉

Believe me or not, I code much faster since I started to do those things. I’m not even talking about CSS preprocessors here. I’m talking about making some default classes in order not to boot from scratch.

And if you’re using a CSS preprocessor, be sure to create a bunch of mixins to start your project with a solid basis. From there, CSS becomes a game again. 😉

### 学分(Credits)

We spoke about a bunch of topics today, so here are some useful resources and references:

05-08

09-12
06-19 1617
05-29 2486
11-30
05-03 882
08-04
07-09
07-07 302
11-17 1234
03-14 749