Tengo una tabla en HTML5 a la que me gustaría agregar una barra de desplazamiento. Quiero que la tabla muestre diez filas y luego el usuario puede desplazarse hacia abajo para ver otras canciones. ¿Cómo puedo agregar la barra de desplazamiento?
Aquí está mi código para la tabla en HTML5:
URL http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw
Aquí está mi código CSS:
#my_table { border-radius: 20px; background-color: transparent; color: black; width: 500px; text-align: center; }
Si tiene que dirigirse a las columnas de su tabla y no desea desplazar esos títulos, esta solución podría ayudarlo a:
Esta solución necesita tags thead
y tbody
dentro del elemento de table
.
table.tableSection { display: table; width: 100%; } table.tableSection thead, table.tableSection tbody { float: left; width: 100%; } table.tableSection tbody { overflow: auto; height: 150px; } table.tableSection tr { width: 100%; display: table; text-align: left; } table.tableSection th, table.tableSection td { width: 33%; }
Violín de trabajo
Con comentarios
Nota : Si está seguro de que la barra de desplazamiento vertical siempre está presente, puede usar la propiedad css3 calc para hacer que las celdas de thead se alineen con las celdas de tbody.
table.tableSection thead { padding-right:18px; /* 18px is approx. value of width of scroll bar */ width: calc(100% - 18px); }
Puede hacer lo mismo detectando la presencia de la barra de desplazamiento usando javascript y aplicando los estilos anteriores.
En lugar de asumir como columnas de ancho fijo.
table.tableSection { display: table; width: 100%; } table.tableSection thead, table.tableSection tbody { width: 100%; } table.tableSection thead { overflow-y: scroll; display: table; table-layout: fixed; width: calc(100% - 16px); /* assuming scrollbar width as 16px */ } table.tableSection tbody { overflow: auto; height: 150px; display: block; } table.tableSection tr { width: 100%; text-align: left; display: table; table-layout: fixed; }
Fiddle de trabajo
Esta es la técnica que he usado en varias ocasiones. Originalmente se basa en este violín con una serie de modificaciones. También es fluido y los anchos de columna se pueden arreglar añadiendo un estilo de ancho al
.
/* this is for the main container of the table, also sets the height of the fixed header row */ .headercontainer { position: relative; border: 1px solid #222; padding-top: 37px; background: #000; } /* this is for the data area that is scrollable */ .tablecontainer { overflow-y: auto; height: 200px; background: #fff; } /* remove default cell borders and ensures table width 100% of its container*/ .tablecontainer table { border-spacing: 0; width:100%; } /* add a thin border to the left of cells, but not the first */ .tablecontainer td + td { border-left:1px solid #eee; } /* cell padding and bottom border */ .tablecontainer td, th { border-bottom:1px solid #eee; padding: 10px; } /* make the default header height 0 and make text invisible */ .tablecontainer th { height: 0px; padding-top: 0; padding-bottom: 0; line-height: 0; visibility: hidden; white-space: nowrap; } /* reposition the divs in the header cells and place in the blank area of the headercontainer */ .tablecontainer th div{ visibility: visible; position: absolute; background: #000; color: #fff; padding: 9px 10px; top: 0; margin-left: -10px; line-height: normal; border-left: 1px solid #222; } /* prevent the left border from above appearing in first div header */ th:first-child div{ border: none; } /* alternate colors for rows */ .tablecontainer tbody tr:nth-child(even){ background-color: #ddd; }
Table attribute name Table attribute name Value Value Description Description align left, center, right Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text bgcolor rgb(x,x,x), #xxxxxx, colorname Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table border 1,"" Specifies whether the table cells should have borders or not cellpadding pixels Not supported in HTML5. Specifies the space between the cell wall and the cell content cellspacing pixels Not supported in HTML5. Specifies the space between cells frame void, above, below, hsides, lhs, rhs, vsides, box, border Not supported in HTML5. Specifies which parts of the outside borders that should be visible rules none, groups, rows, cols, all Not supported in HTML5. Specifies which parts of the inside borders that should be visible summary text Not supported in HTML5. Specifies a summary of the content of a table width pixels, % Not supported in HTML5. Specifies the width of a table
Un año más o menos ha pasado desde que se hizo la pregunta, pero no estaba satisfecho con las respuestas. Estuve jugando un rato, y aquí hay un código que dice:
Demostración en vivo aquí: http://jsbin.com/bagaro/1/edit?html,output .
Scrollabe table This table is scrollable
Name Operator Began operation Tonnage Status
Seabourne Sun Seabourn Cruise Line 1988 ? Ended service in 2002, currently operating as Prinsendam Adventures of the Seas Royal Caribbean International 2001 138,000 Operating Oceanic Independence American Hawaiian Cruises / American Global Line 1974 23,719 Named formerly (1951-1974) and subsequently renamed (1982-2006) the Independence, renamed the Oceanic (2006), sold for scrap in 2008 but remains in mothballs Cunard Ambassador Cunard Line 1972 14,160 Burnt 1974, rebuilt into a livestock carrier, renamed Linda Clausen, later Procyon, Raslan. Scrapped 1984 after a second fire. Aegean Beauty Voyages to Antiquity 1973 11,563 Formerly Aegean Dolphin and Aegean I. Operating Serenade of the Seas Royal Caribbean International 2003 90,090 Operating Queen Elizabeth 2 Cunard Line 1969 70,327 Left fleet in November 2008 National Geographic Endeavour Lindblad Expeditions 1996 Operating, also known as Endeavour Liberty of the Seas Royal Caribbean International 2007 154,407 Operating
usa esta tabla en un DIV
....
.tbl_container{ overflow:auto; width: 500px;height: 200px; }
y además de esto, si quieres hacerlo más hermoso y atractivo, utiliza el jscollpane para personalizar tu barra de desplazamiento.
HTML:
↓ SCROLL ↓
Colonne 1 Colonne 2 Colonne 3 Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo !
↓ SCROLL MORE ↓
Colonne 1 Colonne 2 Colonne 3 Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo ! Non Mais Allo !
↑ UP ↑
CSS:
body{ font:1.2em normal Arial,sans-serif; color:#34495E; } h1{ text-align:center; text-transform:uppercase; letter-spacing:-2px; font-size:2.5em; margin:20px 0; } .container{ width:90%; margin:auto; } table{ border-collapse:collapse; width:100%; } .blue{ border:2px solid #1ABC9C; } .blue thead{ background:#1ABC9C; } .purple{ border:2px solid #9B59B6; } .purple thead{ background:#9B59B6; } thead{ color:white; } th,td{ text-align:center; padding:5px 0; } tbody tr:nth-child(even){ background:#ECF0F1; } tbody tr:hover{ background:#BDC3C7; color:#FFFFFF; } .fixed{ top:0; position:fixed; width:auto; display:none; border:none; } .scrollMore{ margin-top:600px; } .up{ cursor:pointer; }
JS (jQuery):
;(function($) { $.fn.fixMe = function() { return this.each(function() { var $this = $(this), $t_fixed; function init() { $this.wrap(''); $t_fixed = $this.clone(); $t_fixed.find("tbody").remove().end().addClass("fixed").insertBefore($this); resizeFixed(); } function resizeFixed() { $t_fixed.find("th").each(function(index) { $(this).css("width",$this.find("th").eq(index).outerWidth()+"px"); }); } function scrollFixed() { var offset = $(this).scrollTop(), tableOffsetTop = $this.offset().top, tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height(); if(offset < tableOffsetTop || offset > tableOffsetBottom) $t_fixed.hide(); else if(offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is(":hidden")) $t_fixed.show(); } $(window).resize(resizeFixed); $(window).scroll(scrollFixed); init(); }); }; })(jQuery); $(document).ready(function(){ $("table").fixMe(); $(".up").click(function() { $('html, body').animate({ scrollTop: 0 }, 2000); }); });
Para el progtwigdor principiante: si no desea descargar y hospedar jQuery usted mismo, puede incluirlo desde un CDN (Content Delivery Network).
Agregando jQuery a sus páginas web, haga clic aquí .
Referencia: AQUÍ
Usando flexboxes, no javascript, y es receptivo.
/* styles */ table { font-family: sans-serif; border-collapse: collapse; max-height: 300px; overflow: auto; } td, th { border: 1px solid #ddd; text-align: left; padding: 8px; background: #fff; } tr:nth-child(odd) td { background-color: #eee; } /* fixed headers */ table, thead, tbody { display: block; } thead { position: sticky; top: 0; } tr { display: flex; } th, td { flex: 1; min-width: 100px; overflow: hidden; text-overflow: ellipsis; }
HTML Table
# Firstname Lastname Age City Country Sex Example Example ExampleReallyReallyLong Example 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Example Really Really Long ExampleReallyReallyLong Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes 1 Anna Pitt 35 New York USA Female Yes Yes Yes Yes
Puede usar una clase de división con el atributo de desbordamiento utilizando el valor scroll. O puede encerrar la tabla dentro de un iframe. El iframe funciona bien con navegadores IE antiguos y nuevos, pero puede no funcionar con otros navegadores y probablemente no con el último IE.
#myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ } .myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ } Content1 Content2 Content
La respuesta de @jogesh_pi es una buena solución, he creado un ejemplo aquí http://jsfiddle.net/pqgaS/5/ , compruébalo, espero que esto ayude
Data Data Data Data Data Data
#listtableWrapperScroll{ height:100px; width:460px; overflow-y:scroll; border:1px solid #777777; background:#FFFFF2; } #listtableWrapperScroll #listtable{ width:440px; } #listtableWrapperScroll #listtable tr td{ border-bottom:1px dashed #444; }
puedes intentar esto
CSS:
#table-wrapper { height:150px; overflow:auto; margin-top:20px; } #table-wrapper table { width:100%; color:#000; } #table-wrapper table thead th .text { position:fixed; top:0px; height:20px; width:35%; border:1px solid red; }
HTML:
album song genre album 0 song0 genre0 album 1 song 1 genre1 album2 song 2 genre2 album3 song 3 genre3 album4 song 4 genre 4 album5 song 5 genre 5 album 6 song6 genre6 album 7 song7 genre7 album8 song8 genre 8 album9 song9 genre9 album10 song 10 genre10 album11 song 11 genre11 album12 song12 genre12 album 13 song13 genre13 album14 song14 genre14 album15 song15 genre15 album 16 song16 genre16 album 17 song17 genre17 album18 song18 genre18 album19 song19 genre19 album20 song20 genre20
Mira este violín: http://jsfiddle.net/Kritika/GLKxB/1/
esto mantendrá fixed
cabezal de la table
y scroll
solo el table content
la table content
.
Scrollable Table URL http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw http://www.youtube.com/embed/evuSpI2Genw
Mi solución más simple se basa en el diseño de columnas fijas . Tendrá que establecer el ancho de cada columna, por ejemplo: 4 columnas de 100 píxeles cada una es igual a 400 píxeles de ancho total.
table { table-layout: fixed; width: 400px; } td, th { width: 100px; }
El algoritmo de disposición de tabla fija tiene muchas ventajas sobre el algoritmo automático de disposición de tabla (por ejemplo: el diseño horizontal solo depende del ancho de la tabla y el ancho de las columnas, no el contenido de las celdas, permite que un navegador diseñe la tabla más rápido) que el diseño de la tabla automática, el navegador puede comenzar a mostrar la tabla una vez que se ha recibido la primera fila, etc.)
Luego, deberá separar el thead del tbody al forzar su estilo de visualización para block
lugar de la table-*
predeterminada- table-*
thead tr { display: block; } tbody { display: block; height: 256px; overflow-y: auto; }
Eso hará que el tbody
pueda desplazar como una caja separada y el thead
no relacionado con ella. Y esa es la razón principal por la que tuvo que arreglar el ancho de las columnas como se hizo arriba.
Trabajo JsFiddle: https://jsfiddle.net/angiolep/65q1gdcy/1/
Esta fue una pregunta desafiante. Creo que finalmente tengo una solución que cumple con los requisitos completos: una tabla dinámica desplazable vertical y horizontal (dinámica porque puede cambiar la cantidad de filas y columnas, y ninguna celda tiene ancho o altura fijos).
El diseño de HTML y CSS es bastante simple, como han mencionado otras personas. La cuestión clave es volver a calcular (ancho de celda de JavaScript). Y para asegurarme de que el desplazamiento horizontal funciona, también recalculo el ancho del cargador y el cuerpo tbody.
Aquí hay un violín https://jsfiddle.net/jmarcos00/6hv0dsj8/1/
Código HTML:
header one two header three header one two header three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three one data two three
Código CSS:
/* table border rule */ table, td, th { border: 1px solid black; } /* display as block plus display vertical scroll bars */ thead, tbody { display: block; overflow-y: scroll; } /* sample height */ tbody { height: 100px; } /* sample width and horizontal scroll bar */ div { width: 200px; overflow-x: auto; }
Código de JavaScript:
var i, w, wtot, thtot, thw, tdw, theadtr, tbodytr; var th_rect, td_rect, theadtr_rect, tbodytr_rect; var safe = new Array(); // get thead and tbody var mythead = document.getElementById("mythead"); var mytbody = document.getElementById("mytbody"); // get first tr of thead and tbody theadtr = mythead.children[0]; tbodytr = mytbody.children[0]; theadtr_rect = theadtr.getBoundingClientRect(); tbodytr_rect = tbodytr.getBoundingClientRect(); // get width difference of longer first tr // difference between tr and parent if (tbodytr_rect.width > theadtr_rect.width) wtot = mytbody.getBoundingClientRect().width - tbodytr_rect.width; else wtot = mythead.getBoundingClientRect().width - theadtr_rect.width; // get width difference between tr and total th width (first step) thtot = theadtr_rect.width; // get th thead array and td tbody array theadtr = theadtr.children; tbodytr = tbodytr.children; // get loop for (i = 0; i < theadtr.length; i++) { // second step for width difference between tr and total th width th_rect = theadtr[i].getBoundingClientRect(); td_rect = tbodytr[i].getBoundingClientRect(); thtot -= th_rect.width; // get width of each th and first row td (without paddings etc) tdw = parseFloat(window.getComputedStyle(tbodytr[i]).getPropertyValue("width")); thw = parseFloat(window.getComputedStyle(theadtr[i]).getPropertyValue("width")); // get bigger width w = (tdw > thw) ? tdw : thw; safe.push(w); // add to width total (decimal value with paddings etc) w = (tdw > thw) ? td_rect.width : th_rect.width; wtot += w; } // consider tr width and total th width difference wtot += thtot; // set loop for (i = 0; i < theadtr.length; i++) { // set width to th and first row td w = safe[i] + "px"; theadtr[i].style.width = w; tbodytr[i].style.width = w; } // set width for thead and tbody wtot = wtot + "px"; mythead.style.width = wtot; mytbody.style.width = wtot;
Primero probé la respuesta aceptada por el señor Green, pero descubrí que mis columnas no se alineaban, que flotaban: la izquierda parece muy sospechosa. Cuando pasé de no scollbar a scrollbar, mi cuerpo de tabla cambió algunos píxeles y perdí la alineación.
CÓDIGO PEN https://codepen.io/majorp/pen/gjrRMx
CSS .width50px { width: 100px !important; } .width100px { width: 100px !important; } .fixed_headers { width: 100%; table-layout: fixed; border-collapse: collapse; } th { padding: 5px; text-align: left; font-weight:bold; height:50px; } td { padding: 5px; text-align: left; } thead, tr { display: block; position: relative; } tbody { display: block; overflow: auto; width: 100%; height: 500px; } .tableColumnHeader { height: 50px; font-weight: bold; } .lime { background-color: lime; }