CSS中类的顺序是如何工作的?

2021年3月25日11:58:25 发表评论 657 次浏览

许多开发人员都知道CSS中类重写的概念。是的, 的确如此, 但是当涉及到如何覆盖这些类时, 大多数都会感到困惑。类是前端开发的重要资产。因此, 弄清它们非常重要。在类中定义了需要包含在HTML元素中的样式属性, 然后可以使用标记中的"样式"属性来调用样式属性。 style属性支持你提供的尽可能多的值(类), 并且混乱从这里开始!

你是在谈论在块内的同一文件中定义类, 还是从不同的CSS文件中调用类。该规则保持一致。

"它们将工作的类的顺序并不取决于它们在class属性中编写的顺序。而是由它们在块或.css文件中出现的顺序决定"

如果多个类包含相似的属性, 并且它们在同一HTML元素中使用。然后, 将使用最新修改的类来设置元素的样式。

下面的示例说明了类顺序的概念:

例子

<!DOCTYPE html>
< html >
  
< head >
     < title >Specify the order of classes in CSS</ title >
     < style type = "text/css" >
         h1 {
             color: green;
         }
          
         .container {
             width: 600px;
             padding: 5px;
             border: 2px solid black;
         }
          
         .box1 {
             width: 300px;
             height: 50px;
             background-color: purple;
         }
          
         .box2 {
             width: 595px;
             height: 50px;
             background-color: yellow;
         }
     </ style >
</ head >
  
< body >
     < h1 >lsbin</ h1 >
     < b >A Compter Science Portal for Geeks</ b >
     < br >
     < br >
     < div class = "container" >
         < div >
             < input type = "text" class = "box1" value =
             "How is it going everyone, this is box number 1" >
         </ div >
  
         < div >
             < input type = "text" class = "box2" value =
             "This is box number 2" >
         </ div >
  
         < div >
             < input type = "text" class = "box1 box2" value =
"Here we are trying to combine box1 and box2, let us name it box3" >
         </ div >
  
         < div >
             < input type = "text" class = "box2 box1" value=
"This is similar to box number 3, only difference is
  precedence of classes, let us name it box4">
         </ div >
     </ div >
</ body >
  
</ html >

输出如下:

现在,如果你注意到div1和div2分别代表类box1和box2会给你预期的结果。

CSS中类的顺序如何工作?1

但是,对于样式属性为box1 box2的div3,它调用多个CSS类。现在,人们很容易混淆,因为box1首先在div3的样式属性中编写,因此会先被调用,然后一旦box2被调用,它就会覆盖box1。但事实并非如此。如果你仔细查看style .css文件,你会发现box1{}是在box2{}之前定义的,这就是为什么box1会被box2覆盖。对于div4,我们在box1之前调用box2。这个相同的机制可以工作,并在div4块中提供box2的样式。

CSS中类的顺序如何工作?2

注意:请记住, 内联CSS始终比外部和内部CSS优先级更高。因此, 如果在HTML元素中使用内联样式, 则内联样式中定义的属性将覆盖预定义的类。如果你知道, 你可以忽略所有这些事情!重要关键词。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: