css权重导致的样式不生效问题
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <title>Document</title> <script></script> <style> .flex-container { display: flex; color: white; } .flex-container .flex-item { background-color: red; width: 100px; } .sel { background-color: black; } </style> </head> <body style="width: 100%"> <div class="flex-container"> <div class="flex-item sel"> 1 </div> <div class="flex-item"> 2 </div> <div class="flex-item"> 3 </div> </div> </body> </html>
.sel不会生效,因为css先按权重排序,权重大的样式优先使用,权重一样的才按先后顺序
.flex-container .flex-item 有两个选择器,权重是两个相加,所以权重大
改成:
.flex-item {
background-color: red;
width: 100px;
}
.sel {
background-color: black;
}
或者:
.flex-container .flex-item {
background-color: red;
width: 100px;
}
.flex-item.sel {
background-color: black;
}
都可以使sel可以生效