有办法继承css通用代码吗

tzxcd3kk  于 2023-03-25  发布在  其他
关注(0)|答案(2)|浏览(103)
body {
    background-color:#DFE1E1;
    font-family:sans-serif;
     margin-left:30%;
    }
  
    /*1st */
h1:nth-child(1) { 
  color: red;
  border:5px solid rebeccapurple;
  overflow:hidden;
  animation: animate 5s ease-in 1 forwards;
}

    /*2nd */

h1:nth-child(2) { 
  color: red;
  border:5px solid blue;
  overflow:hidden;
  animation: animate 5s ease-in 1 forwards;
}
    /*3rd */

h1:nth-child(3) { 
  color: red;
  border:5px solid green;
  overflow:hidden;
  animation: animate 5s ease-in 1 forwards;
}

@keyframes animate{
  0%{
    width: 0;
  }
  100%{
    width:250px;
  }
}
<h1>A&nbsp;for&nbsp;Apple</h1>
    <h1>B&nbsp;for&nbsp;Blue</h1>
    <h1>C&nbsp;for&nbsp;Car</h1>
    <h1>D&nbsp;for&nbsp;Doctor</h1>
    <h1>E&nbsp;for&nbsp;Egg</h1>
    <h1>F&nbsp;for&nbsp;Frog</h1>
    <h1>G&nbsp;for&nbsp;Girl</h1>

正如你所观察到的,我已经基本上结束了在h1:nth-child标签中复制CSS代码,而不是在border:5 px solid中;标记,所以有人可以展示一种替代方法来减少css代码的重复性。场景如下:苹果A的第n个代码将具有不同的边框颜色,男孩B的第n+1个代码将具有一些其他不同的颜色标签,因此总共26个不同的边框颜色标签

6tr1vspr

6tr1vspr1#

只需使用逗号,来删除CSS重复项,如下所示:

body {
    background-color:#DFE1E1;
    font-family:sans-serif;
     margin-left:30%;
    }

h1:nth-child(1), h1:nth-child(2), h1:nth-child(3) {
  color: red;
  overflow:hidden;
  animation: animate 5s ease-in 1 forwards;
  border: 5px solid;
}
    /*1st */
h1:nth-child(1) { 
  border-color: rebeccapurple;
}

    /*2nd */
h1:nth-child(2) {
  border-color: blue;
}
    /*3rd */

h1:nth-child(3) { 
  border-color: green;
}

@keyframes animate{
  0%{
    width: 0;
  }
  100%{
    width:250px;
  }
}
<h1>A&nbsp;for&nbsp;Apple</h1>
    <h1>B&nbsp;for&nbsp;Blue</h1>
    <h1>C&nbsp;for&nbsp;Car</h1>
    <h1>D&nbsp;for&nbsp;Doctor</h1>
    <h1>E&nbsp;for&nbsp;Egg</h1>
    <h1>F&nbsp;for&nbsp;Frog</h1>
    <h1>G&nbsp;for&nbsp;Girl</h1>

或者,如果你想再次简化它,你可以使用:nth-child(-n+3)来选择子元素的前3个元素,如下所示:

h1:nth-child(-n+3) {
  color: red;
  overflow:hidden;
  animation: animate 5s ease-in 1 forwards;
  border: 5px solid;
}
vxf3dgd4

vxf3dgd42#

你就不能

h1:nth-child(1),
h1:nth-child(2),
h1:nth-child(3) { 
  color: red;
  border-width: 5px;
  border-style: solid;
  overflow: hidden;
  animation: animate 5s ease-in 1 forwards;
}

h1:nth-child(1) {
 border-color: rebeccapurple;
}

h1:nth-child(2) { 
  border-color: blue;
}

h1:nth-child(3) { 
  border-color: green;
}

...

相关问题