标题有点乱,我给大家看一下。假设我在 CSS 文件中有以下内容:
#container_1 {
width:50%;
border:1px solid black;
}
#container_2 {
background-color:red;
padding:5px;
}
如果我希望 container_2 具有 50% 的宽度和 1x 的边框,与 container_1 相同,是否有某种方法可以定义 container_2 的 CSS,同时包含来自 container_1 的 CSS,而实际上不必为container_2 的 CSS?
类似于:
#container_2 {
include:#container_1;
background-color:red;
padding:5px;
}
谢谢
在 css 中,我们不能直接将一个类的属性继承给另一个类,但是为了简化这一点,我们可以像这样编写上面的代码:
#container_1,#container_2 {
width:50%;
border:1px solid black;
}
#container_2 {
background-color:red;
padding:5px;
}
这样,#container_2 将拥有#container_1 的所有属性,除了其独特的属性。
或
我们可以使用 Sass 来做同样的事情,Sass 有一个叫做@mixin 的特性,我们可以在其中实现这一点。
例如
@mixin reset-list {
margin: 0;
padding: 0;
list-style: none;
}
@mixin horizontal-list {
@include reset-list;
li {
display: inline-block;
margin: {
left: -2px;
right: 2em;
}
}
}
更多详情请访问
https://sass-lang.com/documentation/at-rules/mixin