freeCodeCamp/guide/chinese/certifications/responsive-web-design/basic-css/override-class-declarations.../index.md

1.3 KiB
Raw Blame History

title localeTitle
Override Class Declarations by Styling ID Attributes 通过样式ID属性覆盖类声明

通过样式ID属性覆盖类声明

为了理解CSS中的覆盖首先必须了解CSS中的优先原则。

要记住的关键规则是从底部到顶部读取CSS。

一个例子是:


<style> 
  body { 
    background-color: black; 
    font-family: Arial; 
    color: black; 
  } 
  .red-text { 
    color: red; 
  } 
  .blue-text { 
    color: blue; 
  } 
 </style> 
 <h1 class="red-text blue-text">Example</h1> 

在上面的示例中,文本Example将为蓝色,因为最后添加的类是blue-text

记住id属性优先于类,这意味着它排名最高是关键。

您可以通过在类的名称前面添加#来创建id属性,如下所示:


<style> 
  #purple-text { 
    color: purple; 
  } 
 </style> 

下面是一个示例,向您展示如何通过样式ID属性覆盖类声明


<style> 
  body { 
    background-color: black; 
    font-family: Arial; 
    color: black; 
  } 
  .red-text { 
    color: red; 
  } 
  .blue-text { 
    color: blue; 
  } 
  #green-color { 
    color: green; 
  } 
 </style> 
 <h1 id="green-color" class="red-text blue-text">Example</h1> 

这将使文本Example为绿色,因为id属性将始终优先于class声明。