¿Color alternativo de fila de tabla usando CSS?


Estoy usando una tabla con color de fila alternativo con esto.

tr.d0 td {
  background-color: #CC9999;
  color: black;
}
tr.d1 td {
  background-color: #9999CC;
  color: black;
}
<table>
  <tr class="d0">
    <td>One</td>
    <td>one</td>
  </tr>
  <tr class="d1">
    <td>Two</td>
    <td>two</td>
  </tr>
</table>

Aquí estoy usando class para tr, pero quiero usar solo para table. Cuando uso la clase para la tabla, esto se aplica a la alternativa tr.

¿Puedo escribir mi HTML así usando CSS?

<table class="alternate_color">
    <tr><td>One</td><td>one</td></tr>
    <tr><td>Two</td><td>two</td></tr>
    </table>

¿Cómo puedo hacer que las filas tengan "rayas de cebra" usando CSS?

Author: Laurel, 2010-06-21

9 answers

$(document).ready(function()
{
  $("tr:odd").css({
    "background-color":"#000",
    "color":"#fff"});
});
tbody td{
  padding: 30px;
}

tbody tr:nth-child(odd){
  background-color: #4C8BF5;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>13</td>
</tr>
</tbody>
</table>

Hay un selector CSS, realmente un pseudo-selector, llamado nth-child. En pure CSS puedes hacer lo siguiente:

tr:nth-child(even) {
    background-color: #000000;
}

Nota: No hay soporte en IE 8.

O, si tiene jQuery:

$(document).ready(function()
{
  $("tr:even").css("background-color", "#000000");
});
 716
Author: Russell Dias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-15 09:48:39

Tienes la pseudo-clase :nth-child():

table tr:nth-child(odd) td{
}
table tr:nth-child(even) td{
}

En los primeros días de :nth-child() su soporte para el navegador era un poco pobre. Es por eso que establecer class="odd" se convirtió en una técnica tan común. A finales de 2013 me alegra decir que IE6 e IE7 finalmente están muertos (o lo suficientemente enfermos como para dejar de preocuparse) pero IE8 todavía está alrededor-afortunadamente, es la única excepción.

 120
Author: Álvaro González,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-04 16:30:20

Simplemente agregue lo siguiente a su código html (dentro del <head>) y habrá terminado.

HTML:

<style>
      tr:nth-of-type(odd) {
      background-color:#ccc;
    }
</style>

Más fácil y rápido que los ejemplos de jQuery.

 30
Author: bmich72,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 20:02:33

Puedo escribir mi html de esta manera con use css ?

Sí puedes, pero entonces tendrás que usar el :nth-child() pseudo selector (que tiene soporte limitado sin embargo):

table.alternate_color tr:nth-child(odd) td{
   /* styles here */
}
table.alternate_color tr:nth-child(even) td{
   /* styles here */
}
 12
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-21 11:45:24
<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>
 9
Author: Pranay Rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-21 11:43:34

La mayoría de los códigos anteriores no funcionarán con la versión IE. La solución que funciona para IE+ otros navegadores es esta.

   <style type="text/css">
      tr:nth-child(2n) {
             background-color: #FFEBCD;
        }
</style>
 9
Author: Sriwantha Attanayake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-23 08:06:31

Podemos usar reglas CSS impares e pares y el método jQuery para colores de fila alternativos

Usando CSS

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}

Usando jQuery

$(document).ready(function()
{
  $("table tr:odd").css("background", "#ccc");
  $("table tr:even").css("background", "#fff");
});

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}
<table>
  <tr>
    <td>One</td>
    <td>one</td>
   </tr>
  <tr>
    <td>Two</td>
    <td>two</td>
  </tr>
</table>
 7
Author: Santosh Khalse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 07:36:46

Puede usar selectores nth-child(impar/par) sin embargo, no todos los navegadores ( ie 6-8, ff v3.0) admiten estas reglas, por lo que la mayoría de las soluciones recurren a alguna forma de solución javascript/jquery para agregar las clases a las filas para estos navegadores no compatibles para obtener el efecto de raya de tigre.

 3
Author: redsquare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-21 11:41:55

Hay una manera bastante fácil de hacer esto en PHP, si entiendo su consulta, asumo que codifica en PHP y está utilizando CSS y javascript para mejorar la salida.

La salida dinámica de la base de datos llevará un bucle for para iterar a través de los resultados que luego se cargan en la tabla. Simplemente agregue una llamada a una función como esta:

echo "<tr style=".getbgc($i).">";  //this calls the function based on the iteration of the for loop.

Luego agregue la función al archivo de página o biblioteca:

function getbgc($trcount)
{

$blue="\"background-color: #EEFAF6;\"";
$green="\"background-color: #D4F7EB;\"";
$odd=$trcount%2;
    if($odd==1){return $blue;}
    else{return $green;}    

}

Ahora esto alternará dinámicamente entre colores en cada fila de tabla recién generada.

Es mucho más fácil que jugar con CSS que no funciona en todos los navegadores.

Espero que esto ayude.

 3
Author: mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-13 16:06:11