2016-07-19 129 views
0

重新使用常见的CSS规则有一个CSS样式表如下如何在CSS(SASS)

.icon1 { 
    &:after { 
     content:""; 
     float: right; 
     width: 8px; 
     height: 8px; 
     border-radius: 100%;     
     background-color: #4ac102; 
     display: block; 
     position: relative; 
    } 
} 

.icon2 { 
    &:after { 
     content:""; 
     float: right; 
     width: 8px; 
     height: 8px; 
     border-radius: 100%;     
     background-color: #f1342f; 
     display: block;  
     position: relative; 
    } 
} 

.icon3 { 
    &:after { 
     content:""; 
     float: right; 
     width: 8px; 
     height: 8px; 
     border-radius: 100%;     
     background-color: #616a83; 
     display: block;  
     position: relative; 
    } 
} 

正如你可以除了背景色所有其他属性都一样看。我可以重构此代码以使其变干吗?

+0

这是一种题外话这么久。 CodeReview *可能更适合...但首先检查他们的指导。 –

+0

@Paulie_D你为什么会认为它的话题? – Gagan

+0

因为代码起作用。整理它或将它干燥并不是真正的问题。 –

回答

2

您可以使用此Extend/Inheritance

.icons { 
    content:""; 
    float: right; 
    width: 8px; 
    height: 8px; 
    border-radius: 100%;  
    display: block;  
    position: relative; 
    } 

    .icon1 { 
    &:after { 
     @extend .icons;    
     background-color: #4ac102; 
    } 
    } 
    .icon2 { 
    &:after { 
     @extend .icons;    
     background-color: #f1342f; 
    } 
    } 

    .icon3 { 
    &:after { 
     @extend .icons;    
     background-color: #616a83; 
    } 
    } 
+0

爱它..谢谢 – Gagan

2

对于CSS/SCSS的解决方案,无需额外类:

.icon1, .icon2, .icon3 { 
    &:after { 
     /* shared code */ 
    } 
} 

.icon1 { 
    &:after { 
     /* unique code */ 
    } 
} 
+0

您的解决方案的工作原理,但是如果你使用的是sass,你大多会更喜欢使用继承。 –

+0

同意。我发布了一般用法,并且因为OP代码没有使用特定于sass的特性。 – Toby

0

在HTML不是更好地创造一个一流的,这将是图标和还有一个课程仅用于背景颜色? 在这种情况下,您有这样的事情:

<div class="icon icon-1"></div> 
<div class="icon icon-2"></div> 
<div class="icon icon-3"></div> 

和风格,如:

.icon { 
    content:""; 
    float: right; 
    width: 8px; 
    height: 8px; 
    border-radius: 100%;  
    display: block;  
    position: relative; 
    } 


.icon-1{ 
    background-color: #f1342f; 
} 
.icon-2{ 
    background-color: #616a83; 
} 
.icon-3{ 
    background-color: #4ac102; 
}