如何从祖父母标签继承CSS? [英] How to inherit css from grandparent tag?

查看:125
本文介绍了如何从祖父母标签继承CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两层嵌套的div,我想应用包含类 c的div,该div具有与a类相同的div宽度。如果它是父母,那么我想继承将做的工作。但是在这种情况下该怎么办?

I am having a two level nested div and I want to apply the div holding a class "c" with the same width of div with class a. If it is parent then I guess inherit will do the job. But what to be done in this case?

HTML代码:

<div class="a">
  <div class="b">
     <div class="c">

     </div>
  </div>
</div>

CSS代码

.a{
 width:600px;
}
.b{
width:80%;
}
.c{
//needs to inherit width property set for class a without directly mentioning it as 600px
}


推荐答案

不幸的是,您不能在纯CSS中做到这一点,默认情况下,子元素从不继承 width ,您需要指定它,是的,默认情况下,如果您使用块级元素(例如 div p 标签,但是为了继承(重用)祖父母的财产,您可以使用LESS或SASS之类的CSS预处理程序。

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中执行此操作,我们可以做类似的事情

So if you want to do this in SASS we can do something like

.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 的所有属性。 c 。但是有一个问题,当您在SASS中使用表示法时,它也会打印 .a 块,因此,如果您只想将其用于 @extend 目的,则可以编写此选择器

So here it will pick all the properties from .a to .c. But here's a catch, when you use . notation in SASS, it will literally print the .a block as well, so if you want to only use it for @extend purpose, you can write this selector instead

%a {
  width: 600px;
}

.c {
  @extend %a;
}

此处SASS不会打印 .a ,但仅限于 .c 。您可以参考官方文档,以获取更多有关 SASS @extend

Here SASS won't print .a anymore but only .c.You can refer the official docs for more over SASS @extend

您还可以在SASS中定义变量,因此用<$ c定义一个$ c> $ base-width:600px; 并重新使用它也很有意义。如果您仍然希望使用传统CSS,那么我建议您像Manoj建议的那样声明多个类,但是我不会这样做,就好像您在 .a 中声明任何属性一样。而 .c 中的内容将开始变得混乱。

You can also define variables in SASS so defining one with $base-width: 600px; and re using it across can make sense as well. If you still want to stick with traditional CSS than I would recommend you declaring multiple classes just like Manoj suggested but I would not do this as if you are declaring any properties in .a and same in .c things will start getting messy.

这篇关于如何从祖父母标签继承CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆