Unfortunately you cannot do this in pure CSS, by default the child element never inherits the width
, you need to specify it, yes, by default it will span 100% if you use a block level element like a div
or p
tag but inorder to inherit(re use) the property of grand parent you can use CSS pre processors like LESS or SASS..
所以如果你想在 SASS 中做到这一点,我们可以这样做
.a {
width: 600px;
}
.b {
width: 80%;
}
.c {
@extend .a;
//This is still not an inheritance, you are simply pulling in all the
//properties defined in .a to this class
}
所以这里它将选择所有属性.a
to .c
。但这里有一个问题,当你使用.
SASS 中的表示法,它会逐字打印.a
也可以阻止,所以如果你只想将它用于@extend
目的,你可以写这个选择器来代替
%a {
width: 600px;
}
.c {
@extend %a;
}
这里SASS不会打印.a
不再但仅.c
.您可以参考官方文档了解更多信息SASS @extend http://sass-lang.com/documentation/file.SASS_REFERENCE.html#extend
您还可以在 SASS 中定义变量,因此定义一个变量$base-width: 600px;
重新使用它也是有意义的。如果您仍然想坚持使用传统的 CSS,我建议您像 Manoj 建议的那样声明多个类,但我不会这样做,就好像您在中声明任何属性一样.a
和同样的.c
事情会开始变得混乱。