例如:有两个大小 ,外边距相同的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;
}
预览图
原文:https://www.cnblogs.com/hezhilong/p/13710374.html