在另一个类中调用CSS类?

时间:2011-06-13 06:16:21

标签: css class

是否可以将一个CSS类引用为另一个?而不是再次重写所有的CSS代码?

例如,我有这个:

.btn{
    /* Whatever btn related styles I have */
}

.btn:hover{
    box-shadow:0 0 4px black;
}

.btn:active{
    /* This is where I want to reference the '.red' class */
}

.red{
    /* There is a LOT of CSS code here for cross browser gradients */
}

问题是,我已经在某些地方使用了.red类,并且我也希望将相同的渐变样式应用于“活跃的”#。具有.btn类的所有元素的状态...

如果你能帮忙解决(不一定是我要求它的方式),我非常感谢...

2 个答案:

答案 0 :(得分:16)

你实际上不能做一个引用(CSS的主要失败之一),但你可以这样做:

.btn:active, .red {
    /* Block A: Most (or all) of what used to just be in .red below */
}

.btn:active {
    /* Block B: Stuff *just* for .btn:active, if any */
}

.red {
    /* Block C: Stuff *just* for .red, if any */
}

逗号表示块A正文中的定义分别适用于这些选择器的每个,因此它们适用于“:active”的任何“.btn”元素,并且单独使用适用于任何“.red”元素。

B区和C区是可选的。它们适用于您只想应用于给定选择器的任何定义。您通常会在块A之后列出这些,因为相同特异性的规则是从上到下应用的,因此您可以在块B或块C中覆盖块A中的任何内容,这些块将“赢”。

答案 1 :(得分:-1)

用于将类调用到另一个类。

.classA{
 
 }
 .classB .classA:hover{
   visibility: visible;
   /*classA -> onmouseover , classB -> visible*/
 }

 classB{
 visibility: hidden;
 }

示例代码在鼠标悬停时显示弹出窗口

<!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    /* Popup container - can be anything you want */
    .popup {
      position: relative;
      display: inline-block;
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }
    .popup:hover .popuptext{
      visibility: visible;
      -webkit-animation: fadeIn 1s;
      animation: fadeIn 1s;
    /*onmouseover .popup class .popuptext is visible*/
    }
    
    /* The actual popup */
    .popup .popuptext {
      visibility: hidden;
      width: 160px;
      background-color: #555;
      color: #fff;
      text-align: center;
      border-radius: 6px;
      padding: 8px 0;
      position: absolute;
      z-index: 1;
      bottom: 125%;
      left: 50%;
      margin-left: -80px;
    }
    
    /* Popup arrow */
    .popup .popuptext::after {
      content: "";
      position: absolute;
      top: 100%;
      left: 50%;
      margin-left: -5px;
      border-width: 5px;
      border-style: solid;
      border-color: #555 transparent transparent transparent;
    }
    
    
    
    /* Add animation (fade in the popup) */
    @-webkit-keyframes fadeIn {
      from {opacity: 0;} 
      to {opacity: 1;}
    }
    
    @keyframes fadeIn {
      from {opacity: 0;}
      to {opacity:1 ;}
    }
    </style>
    </head>
    <body style="text-align:center">
    
    <h2>Popup</h2>
    
    <div class="popup">over me to toggle the popup!
      <span class="popuptext" id="myPopup">A Simple Popup!         </span>
    </div>
    
    
    
    </body>
    </html>