How to use a class within another CSS class
I have a table, and I want the rows to intersperse colors the way below works perfectly
<style type="text/css">
.tabela_parametros_gerais tr{height: 20px !important;}
.tabela_parametros_gerais tr td{padding-left : 5px;}
.tabela_parametros_gerais tr:hover {background-color: #E4E1C9 !important;}
.tabela_parametros_gerais tr:nth-child(even) {background-color: #FFFFFF;}
.tabela_parametros_gerais tr:nth-child(odd) {background-color: #ECFFEE;}
</style>
The problem is that the colors established there, should come from another class list_cor_sim and list_cor_nao, I saw a way to do this using Less / sass / cs-modules but I can not use them because the project I am modifying does not use, and I can not add - the
Https://stackoverflow.com/questions/4564916/nesting-css-classes
Example of how I would" like " it to work
<style type="text/css">
.cor_hover{background-color: #E4E1C9;}
.list_cor_sim{background-color: #ECFFEE;}
.list_cor_nao{background-color: #FFFFFF;}
.tabela_parametros_gerais tr{height: 20px !important;}
.tabela_parametros_gerais tr td{padding-left : 5px;}
.tabela_parametros_gerais tr:hover {.cor_hover() !important;}
.tabela_parametros_gerais tr:nth-child(even) {.list_cor_nao();}
.tabela_parametros_gerais tr:nth-child(odd) {.list_cor_sim();}
</style>
With javascript, I am not being able to add mouseover and mouseout (addEventListener is not working)
function zebrar() {
var table = document.getElementById("tabela_parametros_gerais");
for (var i = 0, row; row = table.rows[i]; i++) {
var cor;
if(i % 2 === 0){
cor = "list_cor_sim";
}else{
cor = "list_cor_nao";
}
row.classList.add(cor);
}
}
3 answers
The Browser let alone HTML will not process this for you for safety. the easiest mode would be using a view-engine, if not a preprocessor. Apparently you can't use them, to make this change then you must use javascript.
<script>
document.querySelectorAll('.tabela_parametros_gerais tr:nth-child(even)')
.forEach(el => el.classList.add('list-cor-nao'))
document.querySelectorAll('.tabela_parametros_gerais tr:nth-child(odd)')
.forEach(el => el.classList.add('list-cor-sim'))
</script>
I usually insert the classes into the server-side page load.
In php it would look like this:
$result = mysqli_query($CONN,$sql);
$linhas = myslqi_num_rows($result);
for($x=0;$x<$linhas;$x++){
$campo = mysqli_result($result,$x,'campo');
$class_linha = $x % 2?'linha_cor_sim':'linha_cor_nao';
echo "<tr><td class=$class_linha>$campo</td></tr>";
}
I managed to solve as follows
function zebrar() {
var table = document.getElementById("tabela_parametros_gerais");
for (let i = 0, row; row = table.rows[i]; i++) {
let cor = i % 2 === 0 ? 'list_cor_sim' : 'list_cor_nao';
row.classList.add(cor);
row.addEventListener("mouseover", function(){
this.className = 'list_cor_hover';
});
row.addEventListener("mouseout", function(){
this.className = cor;
});
}
}