---
title: "“少用继承，多用组合”之CSS篇"
author: "jarod2008"
date: "2009-04-15T17:08:04Z"
tags: []
slug: "css"
draft: false
lastmod: "2009-04-15T17:08:04Z"
id: 368264
url: "https://jarod2008.iteye.com/blog/368264"
---

继承是 css中经常要用到的技术，好处是可以尽量让页面的代码减少重复利用，但是随时项目越来越大，需求的不断变化，css代码就会变得越来越臃肿，后期难以控 制和维护。其实，css代码和普通程序代码在编写的时候有很多的相似之处，下面我们就用试试用组合的方式是不是能更好的解决这个问题。

下面是一段普通的代码:  
css:

1. .box {
2. border: 1 px   solid #ccc ;
3. font-size: 12 px ;
4. background: #f1f1f1 ;
5. padding: 10 px ;
6. }

html：

1. &lt; div class = " box " &gt; this is  a gray box &lt;/ div &gt;

 

但是这个时候需求增加了，在页面中不仅要有一个灰色的盒子可能还有蓝色的盒子，可能还有绿色，通常我们会说用集成嘛，好我们就做如下更改  
css:

1. .box-gray ,
2. .box-green {
3. border: 1 px   solid #ccc ;
4. font-size: 12 px ;
5. padding: 10 px ;
6. }
7. .box-gray { background: #f1f1f1 }
8. .box-green { background: #66ff66 }

Html:

1. &lt; div class = " box-gray " &gt; this is  a gray box &lt;/ div &gt;
2. &lt; div   class = " box-green " &gt; this is a green box &lt;/ div &gt;

但是这个时候需求又有变化了，根与应用的不同，盒子中有些要用到12号字，有些要用到14号字，有些要变局10px有些要20px，估计这个时候你就要头大了，如果要用用继承css代码就会变得异常的复杂，那我们就来试验一下用组合的方式看能不能解决。  
css:

1. .fs-12 { font-size: 12 px }
2. .fs-14 { font-size: 14 px }
3. .pd-10 { padding: 10 px }
4. .pd-20 { padding: 20 px }
5. .box {
6. border: 1 px   solid #ccc ;
7. }
8. .box.gray { background: #f1f1f1 }
9. .box.green { background: #66ff66 }

Html

1. &lt; div class = " box gray fs-12 pd-20 " &gt; this a gray fontsize12px padding20px box &lt;/ div &gt;
2. &lt; div   class = " box green fs-14 pd-10 " &gt; this a gray fontsize14px padding10px box &lt;/ div &gt;
3. ….

我们看一些虽然 在class上引用了几个，但是代码和逻辑都非常清晰，而且非常容易维护，随意组合随意扩展。从上面可以看到“组合”的方式是不言而喻的，但是也不是十全 十美的，再拆分组合的时候一定不要过度，不然效果可能适得其反，只有把组合+继承运用的恰到好处才能让我们的代码更加优雅和艺术。