【问题标题】:Inherit class within the CSS在 CSS 中继承类
【发布时间】:2014-05-07 21:14:30
【问题描述】:

假设在 CSS 中有两个类 - fatherDivchildDiv -

.fatherDiv {
    /*
        With background and no special font color 
        */
    background-color: #b0c4de;
    width: 350px;
    height: 280px;
}

.childDiv {

    font-family: Arial,Helvetica,sans-serif;
    font-size: 50px;
}

并希望.childDiv 继承所有.fatherDiv 样式并添加更多。

常见的做法是这样做——

<div class="fatherDiv childDiv">I'm the Child</div>

但我的问题是——

是否可以选择将类样式继承到 CSS 文件中的另一个类?

我试过了——

style.css -

.fatherDiv .childDiv {
    /*
          Inherit from .fatherDiv ...  
            */
    font-family: Arial,Helvetica,sans-serif;
    font-size: 50px;
}

index.html -

<div class="childDiv">I'm the Child</div>

Here is its jsFiddle

但它丢弃了干扰。

【问题讨论】:

  • 您的查询不清楚。

标签: html css inheritance


【解决方案1】:

你可以这样做:

.fatherDiv, .childDiv {
    background-color: #b0c4de;
    width: 350px;
    height: 280px;
}

.childDiv
{
    font-family: Arial,Helvetica,sans-serif;
    font-size: 50px;
}

http://jsfiddle.net/NicoO/9rhDd/6/

您也可以不将这些元素称为childfather。他们是兄弟姐妹。

【讨论】:

    【解决方案2】:

    检查这个 -http://jsfiddle.net/9rhDd/7/

     .fatherDiv,.childDiv {
        /*
            With background and no special font color 
            */
        background-color:#b0c4de;
        width:350px;
        height:280px;
        /*font-size:50px;*/
    }
    

    【讨论】:

      【解决方案3】:

      类似:

      .fatherDiv {
          background-color: #b0c4de;
          width: 350px;
          height: 280px;
      }
      
      .childDiv {
          background-color:inherit;
          width:100%;
          height:100%;
          font-family: Arial,Helvetica,sans-serif;
          font-size: 50px;
      }
      

      只要你的 HTML 是这样的,理论上就可以工作:

      <div class="fatherDiv">
         <div class="childDiv"></div>
      </div>
      

      虽然inherit 并非对所有 CSS 值都有效,但您必须检查一下。

      它不会自动继承值,您需要像 Sass 这样的预处理器才能做到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        • 2019-12-28
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 2011-08-29
        相关资源
        最近更新 更多