1 OOCSS的定义:

Object Oriented css(面向对象css)的缩写,是一种用最简单的方式编写的CSS代码,从而使代码 重用性,可维护性和可扩展性更好的书写方法。

 

2 OOCSS的用法:

例如:有两个大小 ,外边距相同的div。

 

 

 

 我们可以这样写代码

.box1{
    
    
    width: 30%;
    margin-left: 35%;
    height: 300px;
    margin-top: 50px;
    text-align: center;
    line-height: 300px;
    color: white;
    background-color: #8A2BE2;
    font-size: 22px;
    

}

.box2{
    
    width: 30%;
    margin-left: 35%;
    height: 300px;
    margin-top: 50px;
    text-align: center;
    line-height: 300px;
    color: white;
    background-color: blue;
    font-size: 23px;
}

 

但是,其中有很多代码是相同的, 所以上边这种写法会增加很多工作量而且也不便于维护,所以一般我们也会这样写,代码如下

.box1,.box2{
    
    width: 30%;
    margin-left: 35%;
    height: 300px;
    margin-top: 50px;
    text-align: center;
    line-height: 300px;
    color: white;
}

.box1{
    
    background-color: #8A2BE2;
    font-size: 22px;
    

}

.box2{ background
-color: blue; font-size: 23px; }

   

这样把重复的css代码拿出来,单独写一个样式表,然后将有相同样式的类添加到这个样式里就行,

但是后期如果再增加一个相同的div的时候就需要重新进入样式表添加类,如果是大型网站的话 这样也会降低我们的工作效率,所以我们这时候就需要利用OOCSS写法来降低维护难度及工作量。

写法很简单,只要将重复的样式拿出来单独写一个类,然后将类嵌入到HTML代码中就可以了,代码如下:

 

1)样式表代码

.box1{
    
    background-color: #8A2BE2;
    font-size: 22px;
    
}

.box2{
    
    background-color: blue;
    font-size: 23px;
}

.oocss1{
    width: 30%;
    margin-left: 35%;
    height: 300px;
    margin-top: 50px;
    text-align: center;
    line-height: 300px;
    color: white;
}

 

2) HTML 代码(在类里边空格+重复样式类.OOCSS1就可以调用重复样式了):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>测试最小空间</title>
        <link rel="stylesheet" href="测试最小空间.css">
    </head>
    <body>
        
            <div class="box1 oocss1">Div1</div>
            <div class="box2 oocss1">Div2</div>
        
    </body>
</html>

 

后期我们继续增加相同的div,只要在Html代码中嵌入 oocss1类就可以了,不同的地方可以在类 box3中进行添加,代码及预览图如下

 

Html代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>测试最小空间</title>
        <link rel="stylesheet" href="测试最小空间.css">
    </head>
    <body>
        
            <div class="box1 oocss1">Div1</div>
            <div class="box2 oocss1">Div2</div>
            <div class="box3 oocss1">Div3</div>
        
    </body>
</html>

 

css代码

.box1{
    
    background-color: #8A2BE2;
    font-size: 22px;
    
}

.box2{
    
    background-color: blue;
    font-size: 23px;
}

.box3{
    background-color: deeppink;
    font-size:25px
}

.oocss1{
    width: 30%;
    margin-left: 35%;
    height: 300px;
    margin-top: 50px;
    text-align: center;
    line-height: 300px;
    color: white;
}

 

 

预览图

 

 

 

注意:

1)在 OOCSS 的观念中,强调重复使用 class,而应该避免使用 id 作为 CSS 的选择器。
 
2)用OOCSS样式的时候,需要提前确定重复样式或者将重复样式尽量进行拆分,这样便于后续调用重复样式,否则有一个样式不同,就没法调用这个重复样式
 
 
 

3 OOCSS的优缺点

1 优点:

  • css代码减少,降低工作量。
  • 样式重复利用,代码简洁,便于维护。
  • 代码少,加载速度快。
  • 能轻松构造新的页面布局,或制作新的页面风格

 

2 缺点:

  • 适用于大型网站项目(重复组件,样式多),小型项目优势不明显(代码少,可以直接利用第二种普通写法)。
  • 需要熟练运用,因为特定要求(强调重复使用类选择器,避免使用id选择器)如果运用不得当,反而可能会造成后续维护困难,所以最好写上注释。